babylon.no-module.max.js 4.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561
  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)];
  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._observers.splice(index, 1);
  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._observers.splice(index, 1);
  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. /**
  8221. * Notify all Observers by calling their respective callback with the given data
  8222. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8223. * @param eventData defines the data to send to all observers
  8224. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8225. * @param target defines the original target of the state
  8226. * @param currentTarget defines the current target of the state
  8227. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8228. */
  8229. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8230. if (mask === void 0) { mask = -1; }
  8231. if (!this._observers.length) {
  8232. return true;
  8233. }
  8234. var state = this._eventState;
  8235. state.mask = mask;
  8236. state.target = target;
  8237. state.currentTarget = currentTarget;
  8238. state.skipNextObservers = false;
  8239. state.lastReturnValue = eventData;
  8240. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8241. var obs = _a[_i];
  8242. if (obs._willBeUnregistered) {
  8243. continue;
  8244. }
  8245. if (obs.mask & mask) {
  8246. if (obs.scope) {
  8247. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8248. }
  8249. else {
  8250. state.lastReturnValue = obs.callback(eventData, state);
  8251. }
  8252. if (obs.unregisterOnNextCall) {
  8253. this._deferUnregister(obs);
  8254. }
  8255. }
  8256. if (state.skipNextObservers) {
  8257. return false;
  8258. }
  8259. }
  8260. return true;
  8261. };
  8262. /**
  8263. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8264. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8265. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8266. * and it is crucial that all callbacks will be executed.
  8267. * The order of the callbacks is kept, callbacks are not executed parallel.
  8268. *
  8269. * @param eventData The data to be sent to each callback
  8270. * @param mask is used to filter observers defaults to -1
  8271. * @param target defines the callback target (see EventState)
  8272. * @param currentTarget defines he current object in the bubbling phase
  8273. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8274. */
  8275. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8276. var _this = this;
  8277. if (mask === void 0) { mask = -1; }
  8278. // create an empty promise
  8279. var p = Promise.resolve(eventData);
  8280. // no observers? return this promise.
  8281. if (!this._observers.length) {
  8282. return p;
  8283. }
  8284. var state = this._eventState;
  8285. state.mask = mask;
  8286. state.target = target;
  8287. state.currentTarget = currentTarget;
  8288. state.skipNextObservers = false;
  8289. // execute one callback after another (not using Promise.all, the order is important)
  8290. this._observers.forEach(function (obs) {
  8291. if (state.skipNextObservers) {
  8292. return;
  8293. }
  8294. if (obs._willBeUnregistered) {
  8295. return;
  8296. }
  8297. if (obs.mask & mask) {
  8298. if (obs.scope) {
  8299. p = p.then(function (lastReturnedValue) {
  8300. state.lastReturnValue = lastReturnedValue;
  8301. return obs.callback.apply(obs.scope, [eventData, state]);
  8302. });
  8303. }
  8304. else {
  8305. p = p.then(function (lastReturnedValue) {
  8306. state.lastReturnValue = lastReturnedValue;
  8307. return obs.callback(eventData, state);
  8308. });
  8309. }
  8310. if (obs.unregisterOnNextCall) {
  8311. _this._deferUnregister(obs);
  8312. }
  8313. }
  8314. });
  8315. // return the eventData
  8316. return p.then(function () { return eventData; });
  8317. };
  8318. /**
  8319. * Notify a specific observer
  8320. * @param observer defines the observer to notify
  8321. * @param eventData defines the data to be sent to each callback
  8322. * @param mask is used to filter observers defaults to -1
  8323. */
  8324. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8325. if (mask === void 0) { mask = -1; }
  8326. var state = this._eventState;
  8327. state.mask = mask;
  8328. state.skipNextObservers = false;
  8329. observer.callback(eventData, state);
  8330. };
  8331. /**
  8332. * Gets a boolean indicating if the observable has at least one observer
  8333. * @returns true is the Observable has at least one Observer registered
  8334. */
  8335. Observable.prototype.hasObservers = function () {
  8336. return this._observers.length > 0;
  8337. };
  8338. /**
  8339. * Clear the list of observers
  8340. */
  8341. Observable.prototype.clear = function () {
  8342. this._observers = new Array();
  8343. this._onObserverAdded = null;
  8344. };
  8345. /**
  8346. * Clone the current observable
  8347. * @returns a new observable
  8348. */
  8349. Observable.prototype.clone = function () {
  8350. var result = new Observable();
  8351. result._observers = this._observers.slice(0);
  8352. return result;
  8353. };
  8354. /**
  8355. * Does this observable handles observer registered with a given mask
  8356. * @param mask defines the mask to be tested
  8357. * @return whether or not one observer registered with the given mask is handeled
  8358. **/
  8359. Observable.prototype.hasSpecificMask = function (mask) {
  8360. if (mask === void 0) { mask = -1; }
  8361. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8362. var obs = _a[_i];
  8363. if (obs.mask & mask || obs.mask === mask) {
  8364. return true;
  8365. }
  8366. }
  8367. return false;
  8368. };
  8369. return Observable;
  8370. }());
  8371. BABYLON.Observable = Observable;
  8372. })(BABYLON || (BABYLON = {}));
  8373. //# sourceMappingURL=babylon.observable.js.map
  8374. var BABYLON;
  8375. (function (BABYLON) {
  8376. var SmartArray = /** @class */ (function () {
  8377. function SmartArray(capacity) {
  8378. this.length = 0;
  8379. this.data = new Array(capacity);
  8380. this._id = SmartArray._GlobalId++;
  8381. }
  8382. SmartArray.prototype.push = function (value) {
  8383. this.data[this.length++] = value;
  8384. if (this.length > this.data.length) {
  8385. this.data.length *= 2;
  8386. }
  8387. };
  8388. SmartArray.prototype.forEach = function (func) {
  8389. for (var index = 0; index < this.length; index++) {
  8390. func(this.data[index]);
  8391. }
  8392. };
  8393. SmartArray.prototype.sort = function (compareFn) {
  8394. this.data.sort(compareFn);
  8395. };
  8396. SmartArray.prototype.reset = function () {
  8397. this.length = 0;
  8398. };
  8399. SmartArray.prototype.dispose = function () {
  8400. this.reset();
  8401. if (this.data) {
  8402. this.data.length = 0;
  8403. this.data = [];
  8404. }
  8405. };
  8406. SmartArray.prototype.concat = function (array) {
  8407. if (array.length === 0) {
  8408. return;
  8409. }
  8410. if (this.length + array.length > this.data.length) {
  8411. this.data.length = (this.length + array.length) * 2;
  8412. }
  8413. for (var index = 0; index < array.length; index++) {
  8414. this.data[this.length++] = (array.data || array)[index];
  8415. }
  8416. };
  8417. SmartArray.prototype.indexOf = function (value) {
  8418. var position = this.data.indexOf(value);
  8419. if (position >= this.length) {
  8420. return -1;
  8421. }
  8422. return position;
  8423. };
  8424. SmartArray.prototype.contains = function (value) {
  8425. return this.data.indexOf(value) !== -1;
  8426. };
  8427. // Statics
  8428. SmartArray._GlobalId = 0;
  8429. return SmartArray;
  8430. }());
  8431. BABYLON.SmartArray = SmartArray;
  8432. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8433. __extends(SmartArrayNoDuplicate, _super);
  8434. function SmartArrayNoDuplicate() {
  8435. var _this = _super !== null && _super.apply(this, arguments) || this;
  8436. _this._duplicateId = 0;
  8437. return _this;
  8438. }
  8439. SmartArrayNoDuplicate.prototype.push = function (value) {
  8440. _super.prototype.push.call(this, value);
  8441. if (!value.__smartArrayFlags) {
  8442. value.__smartArrayFlags = {};
  8443. }
  8444. value.__smartArrayFlags[this._id] = this._duplicateId;
  8445. };
  8446. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8447. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8448. return false;
  8449. }
  8450. this.push(value);
  8451. return true;
  8452. };
  8453. SmartArrayNoDuplicate.prototype.reset = function () {
  8454. _super.prototype.reset.call(this);
  8455. this._duplicateId++;
  8456. };
  8457. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8458. if (array.length === 0) {
  8459. return;
  8460. }
  8461. if (this.length + array.length > this.data.length) {
  8462. this.data.length = (this.length + array.length) * 2;
  8463. }
  8464. for (var index = 0; index < array.length; index++) {
  8465. var item = (array.data || array)[index];
  8466. this.pushNoDuplicate(item);
  8467. }
  8468. };
  8469. return SmartArrayNoDuplicate;
  8470. }(SmartArray));
  8471. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8472. })(BABYLON || (BABYLON = {}));
  8473. //# sourceMappingURL=babylon.smartArray.js.map
  8474. var BABYLON;
  8475. (function (BABYLON) {
  8476. /** Class used to store color gradient */
  8477. var ColorGradient = /** @class */ (function () {
  8478. function ColorGradient() {
  8479. }
  8480. return ColorGradient;
  8481. }());
  8482. BABYLON.ColorGradient = ColorGradient;
  8483. /** Class used to store factor gradient */
  8484. var FactorGradient = /** @class */ (function () {
  8485. function FactorGradient() {
  8486. }
  8487. return FactorGradient;
  8488. }());
  8489. BABYLON.FactorGradient = FactorGradient;
  8490. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8491. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8492. var LoadFileError = /** @class */ (function (_super) {
  8493. __extends(LoadFileError, _super);
  8494. function LoadFileError(message, request) {
  8495. var _this = _super.call(this, message) || this;
  8496. _this.request = request;
  8497. _this.name = "LoadFileError";
  8498. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8499. return _this;
  8500. }
  8501. // Polyfill for Object.setPrototypeOf if necessary.
  8502. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8503. return LoadFileError;
  8504. }(Error));
  8505. BABYLON.LoadFileError = LoadFileError;
  8506. var RetryStrategy = /** @class */ (function () {
  8507. function RetryStrategy() {
  8508. }
  8509. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8510. if (maxRetries === void 0) { maxRetries = 3; }
  8511. if (baseInterval === void 0) { baseInterval = 500; }
  8512. return function (url, request, retryIndex) {
  8513. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8514. return -1;
  8515. }
  8516. return Math.pow(2, retryIndex) * baseInterval;
  8517. };
  8518. };
  8519. return RetryStrategy;
  8520. }());
  8521. BABYLON.RetryStrategy = RetryStrategy;
  8522. // Screenshots
  8523. var screenshotCanvas;
  8524. var cloneValue = function (source, destinationObject) {
  8525. if (!source)
  8526. return null;
  8527. if (source instanceof BABYLON.Mesh) {
  8528. return null;
  8529. }
  8530. if (source instanceof BABYLON.SubMesh) {
  8531. return source.clone(destinationObject);
  8532. }
  8533. else if (source.clone) {
  8534. return source.clone();
  8535. }
  8536. return null;
  8537. };
  8538. var Tools = /** @class */ (function () {
  8539. function Tools() {
  8540. }
  8541. /**
  8542. * Interpolates between a and b via alpha
  8543. * @param a The lower value (returned when alpha = 0)
  8544. * @param b The upper value (returned when alpha = 1)
  8545. * @param alpha The interpolation-factor
  8546. * @return The mixed value
  8547. */
  8548. Tools.Mix = function (a, b, alpha) {
  8549. return a * (1 - alpha) + b * alpha;
  8550. };
  8551. Tools.Instantiate = function (className) {
  8552. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8553. return Tools.RegisteredExternalClasses[className];
  8554. }
  8555. var arr = className.split(".");
  8556. var fn = (window || this);
  8557. for (var i = 0, len = arr.length; i < len; i++) {
  8558. fn = fn[arr[i]];
  8559. }
  8560. if (typeof fn !== "function") {
  8561. return null;
  8562. }
  8563. return fn;
  8564. };
  8565. /**
  8566. * Provides a slice function that will work even on IE
  8567. * @param data defines the array to slice
  8568. * @param start defines the start of the data (optional)
  8569. * @param end defines the end of the data (optional)
  8570. * @returns the new sliced array
  8571. */
  8572. Tools.Slice = function (data, start, end) {
  8573. if (data.slice) {
  8574. return data.slice(start, end);
  8575. }
  8576. return Array.prototype.slice.call(data, start, end);
  8577. };
  8578. Tools.SetImmediate = function (action) {
  8579. if (window.setImmediate) {
  8580. window.setImmediate(action);
  8581. }
  8582. else {
  8583. setTimeout(action, 1);
  8584. }
  8585. };
  8586. Tools.IsExponentOfTwo = function (value) {
  8587. var count = 1;
  8588. do {
  8589. count *= 2;
  8590. } while (count < value);
  8591. return count === value;
  8592. };
  8593. /**
  8594. * Returns the nearest 32-bit single precision float representation of a Number
  8595. * @param value A Number. If the parameter is of a different type, it will get converted
  8596. * to a number or to NaN if it cannot be converted
  8597. * @returns number
  8598. */
  8599. Tools.FloatRound = function (value) {
  8600. if (Math.fround) {
  8601. return Math.fround(value);
  8602. }
  8603. return (Tools._tmpFloatArray[0] = value);
  8604. };
  8605. /**
  8606. * Find the next highest power of two.
  8607. * @param x Number to start search from.
  8608. * @return Next highest power of two.
  8609. */
  8610. Tools.CeilingPOT = function (x) {
  8611. x--;
  8612. x |= x >> 1;
  8613. x |= x >> 2;
  8614. x |= x >> 4;
  8615. x |= x >> 8;
  8616. x |= x >> 16;
  8617. x++;
  8618. return x;
  8619. };
  8620. /**
  8621. * Find the next lowest power of two.
  8622. * @param x Number to start search from.
  8623. * @return Next lowest power of two.
  8624. */
  8625. Tools.FloorPOT = function (x) {
  8626. x = x | (x >> 1);
  8627. x = x | (x >> 2);
  8628. x = x | (x >> 4);
  8629. x = x | (x >> 8);
  8630. x = x | (x >> 16);
  8631. return x - (x >> 1);
  8632. };
  8633. /**
  8634. * Find the nearest power of two.
  8635. * @param x Number to start search from.
  8636. * @return Next nearest power of two.
  8637. */
  8638. Tools.NearestPOT = function (x) {
  8639. var c = Tools.CeilingPOT(x);
  8640. var f = Tools.FloorPOT(x);
  8641. return (c - x) > (x - f) ? f : c;
  8642. };
  8643. Tools.GetExponentOfTwo = function (value, max, mode) {
  8644. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8645. var pot;
  8646. switch (mode) {
  8647. case BABYLON.Engine.SCALEMODE_FLOOR:
  8648. pot = Tools.FloorPOT(value);
  8649. break;
  8650. case BABYLON.Engine.SCALEMODE_NEAREST:
  8651. pot = Tools.NearestPOT(value);
  8652. break;
  8653. case BABYLON.Engine.SCALEMODE_CEILING:
  8654. default:
  8655. pot = Tools.CeilingPOT(value);
  8656. break;
  8657. }
  8658. return Math.min(pot, max);
  8659. };
  8660. Tools.GetFilename = function (path) {
  8661. var index = path.lastIndexOf("/");
  8662. if (index < 0)
  8663. return path;
  8664. return path.substring(index + 1);
  8665. };
  8666. /**
  8667. * Extracts the "folder" part of a path (everything before the filename).
  8668. * @param uri The URI to extract the info from
  8669. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8670. * @returns The "folder" part of the path
  8671. */
  8672. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8673. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8674. var index = uri.lastIndexOf("/");
  8675. if (index < 0) {
  8676. if (returnUnchangedIfNoSlash) {
  8677. return uri;
  8678. }
  8679. return "";
  8680. }
  8681. return uri.substring(0, index + 1);
  8682. };
  8683. Tools.GetDOMTextContent = function (element) {
  8684. var result = "";
  8685. var child = element.firstChild;
  8686. while (child) {
  8687. if (child.nodeType === 3) {
  8688. result += child.textContent;
  8689. }
  8690. child = child.nextSibling;
  8691. }
  8692. return result;
  8693. };
  8694. Tools.ToDegrees = function (angle) {
  8695. return angle * 180 / Math.PI;
  8696. };
  8697. Tools.ToRadians = function (angle) {
  8698. return angle * Math.PI / 180;
  8699. };
  8700. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8701. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8702. var output = "";
  8703. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8704. var i = 0;
  8705. var bytes = new Uint8Array(buffer);
  8706. while (i < bytes.length) {
  8707. chr1 = bytes[i++];
  8708. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8709. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8710. enc1 = chr1 >> 2;
  8711. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8712. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8713. enc4 = chr3 & 63;
  8714. if (isNaN(chr2)) {
  8715. enc3 = enc4 = 64;
  8716. }
  8717. else if (isNaN(chr3)) {
  8718. enc4 = 64;
  8719. }
  8720. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8721. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8722. }
  8723. return "data:image/png;base64," + output;
  8724. };
  8725. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8726. if (bias === void 0) { bias = null; }
  8727. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8728. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8729. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8730. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8731. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8732. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8733. }
  8734. if (bias) {
  8735. minimum.x -= minimum.x * bias.x + bias.y;
  8736. minimum.y -= minimum.y * bias.x + bias.y;
  8737. minimum.z -= minimum.z * bias.x + bias.y;
  8738. maximum.x += maximum.x * bias.x + bias.y;
  8739. maximum.y += maximum.y * bias.x + bias.y;
  8740. maximum.z += maximum.z * bias.x + bias.y;
  8741. }
  8742. return {
  8743. minimum: minimum,
  8744. maximum: maximum
  8745. };
  8746. };
  8747. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8748. if (bias === void 0) { bias = null; }
  8749. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8750. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8751. if (!stride) {
  8752. stride = 3;
  8753. }
  8754. for (var index = start; index < start + count; index++) {
  8755. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8756. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8757. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8758. }
  8759. if (bias) {
  8760. minimum.x -= minimum.x * bias.x + bias.y;
  8761. minimum.y -= minimum.y * bias.x + bias.y;
  8762. minimum.z -= minimum.z * bias.x + bias.y;
  8763. maximum.x += maximum.x * bias.x + bias.y;
  8764. maximum.y += maximum.y * bias.x + bias.y;
  8765. maximum.z += maximum.z * bias.x + bias.y;
  8766. }
  8767. return {
  8768. minimum: minimum,
  8769. maximum: maximum
  8770. };
  8771. };
  8772. Tools.Vector2ArrayFeeder = function (array) {
  8773. return function (index) {
  8774. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8775. var length = isFloatArray ? array.length / 2 : array.length;
  8776. if (index >= length) {
  8777. return null;
  8778. }
  8779. if (isFloatArray) {
  8780. var fa = array;
  8781. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8782. }
  8783. var a = array;
  8784. return a[index];
  8785. };
  8786. };
  8787. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8788. if (bias === void 0) { bias = null; }
  8789. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8790. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8791. var i = 0;
  8792. var cur = feeder(i++);
  8793. while (cur) {
  8794. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8795. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8796. cur = feeder(i++);
  8797. }
  8798. if (bias) {
  8799. minimum.x -= minimum.x * bias.x + bias.y;
  8800. minimum.y -= minimum.y * bias.x + bias.y;
  8801. maximum.x += maximum.x * bias.x + bias.y;
  8802. maximum.y += maximum.y * bias.x + bias.y;
  8803. }
  8804. return {
  8805. minimum: minimum,
  8806. maximum: maximum
  8807. };
  8808. };
  8809. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8810. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8811. return null;
  8812. return Array.isArray(obj) ? obj : [obj];
  8813. };
  8814. // Misc.
  8815. Tools.GetPointerPrefix = function () {
  8816. var eventPrefix = "pointer";
  8817. // Check if pointer events are supported
  8818. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8819. eventPrefix = "mouse";
  8820. }
  8821. return eventPrefix;
  8822. };
  8823. /**
  8824. * @param func - the function to be called
  8825. * @param requester - the object that will request the next frame. Falls back to window.
  8826. */
  8827. Tools.QueueNewFrame = function (func, requester) {
  8828. if (!Tools.IsWindowObjectExist()) {
  8829. return setTimeout(func, 16);
  8830. }
  8831. if (!requester) {
  8832. requester = window;
  8833. }
  8834. if (requester.requestAnimationFrame) {
  8835. return requester.requestAnimationFrame(func);
  8836. }
  8837. else if (requester.msRequestAnimationFrame) {
  8838. return requester.msRequestAnimationFrame(func);
  8839. }
  8840. else if (requester.webkitRequestAnimationFrame) {
  8841. return requester.webkitRequestAnimationFrame(func);
  8842. }
  8843. else if (requester.mozRequestAnimationFrame) {
  8844. return requester.mozRequestAnimationFrame(func);
  8845. }
  8846. else if (requester.oRequestAnimationFrame) {
  8847. return requester.oRequestAnimationFrame(func);
  8848. }
  8849. else {
  8850. return window.setTimeout(func, 16);
  8851. }
  8852. };
  8853. Tools.RequestFullscreen = function (element) {
  8854. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8855. if (!requestFunction)
  8856. return;
  8857. requestFunction.call(element);
  8858. };
  8859. Tools.ExitFullscreen = function () {
  8860. if (document.exitFullscreen) {
  8861. document.exitFullscreen();
  8862. }
  8863. else if (document.mozCancelFullScreen) {
  8864. document.mozCancelFullScreen();
  8865. }
  8866. else if (document.webkitCancelFullScreen) {
  8867. document.webkitCancelFullScreen();
  8868. }
  8869. else if (document.msCancelFullScreen) {
  8870. document.msCancelFullScreen();
  8871. }
  8872. };
  8873. Tools.SetCorsBehavior = function (url, element) {
  8874. if (url && url.indexOf("data:") === 0) {
  8875. return;
  8876. }
  8877. if (Tools.CorsBehavior) {
  8878. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8879. element.crossOrigin = Tools.CorsBehavior;
  8880. }
  8881. else {
  8882. var result = Tools.CorsBehavior(url);
  8883. if (result) {
  8884. element.crossOrigin = result;
  8885. }
  8886. }
  8887. }
  8888. };
  8889. // External files
  8890. Tools.CleanUrl = function (url) {
  8891. url = url.replace(/#/mg, "%23");
  8892. return url;
  8893. };
  8894. /**
  8895. * Loads an image as an HTMLImageElement.
  8896. * @param input url string, ArrayBuffer, or Blob to load
  8897. * @param onLoad callback called when the image successfully loads
  8898. * @param onError callback called when the image fails to load
  8899. * @param database database for caching
  8900. * @returns the HTMLImageElement of the loaded image
  8901. */
  8902. Tools.LoadImage = function (input, onLoad, onError, database) {
  8903. var url;
  8904. var usingObjectURL = false;
  8905. if (input instanceof ArrayBuffer) {
  8906. url = URL.createObjectURL(new Blob([input]));
  8907. usingObjectURL = true;
  8908. }
  8909. else if (input instanceof Blob) {
  8910. url = URL.createObjectURL(input);
  8911. usingObjectURL = true;
  8912. }
  8913. else {
  8914. url = Tools.CleanUrl(input);
  8915. url = Tools.PreprocessUrl(input);
  8916. }
  8917. var img = new Image();
  8918. Tools.SetCorsBehavior(url, img);
  8919. var loadHandler = function () {
  8920. if (usingObjectURL && img.src) {
  8921. URL.revokeObjectURL(img.src);
  8922. }
  8923. img.removeEventListener("load", loadHandler);
  8924. img.removeEventListener("error", errorHandler);
  8925. onLoad(img);
  8926. };
  8927. var errorHandler = function (err) {
  8928. if (usingObjectURL && img.src) {
  8929. URL.revokeObjectURL(img.src);
  8930. }
  8931. img.removeEventListener("load", loadHandler);
  8932. img.removeEventListener("error", errorHandler);
  8933. Tools.Error("Error while trying to load image: " + input);
  8934. if (onError) {
  8935. onError("Error while trying to load image: " + input, err);
  8936. }
  8937. };
  8938. img.addEventListener("load", loadHandler);
  8939. img.addEventListener("error", errorHandler);
  8940. var noIndexedDB = function () {
  8941. img.src = url;
  8942. };
  8943. var loadFromIndexedDB = function () {
  8944. if (database) {
  8945. database.loadImageFromDB(url, img);
  8946. }
  8947. };
  8948. //ANY database to do!
  8949. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8950. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8951. }
  8952. else {
  8953. if (url.indexOf("file:") !== -1) {
  8954. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8955. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8956. try {
  8957. var blobURL;
  8958. try {
  8959. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8960. }
  8961. catch (ex) {
  8962. // Chrome doesn't support oneTimeOnly parameter
  8963. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8964. }
  8965. img.src = blobURL;
  8966. usingObjectURL = true;
  8967. }
  8968. catch (e) {
  8969. img.src = "";
  8970. }
  8971. return img;
  8972. }
  8973. }
  8974. noIndexedDB();
  8975. }
  8976. return img;
  8977. };
  8978. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8979. url = Tools.CleanUrl(url);
  8980. url = Tools.PreprocessUrl(url);
  8981. // If file and file input are set
  8982. if (url.indexOf("file:") !== -1) {
  8983. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8984. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8985. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8986. }
  8987. }
  8988. var loadUrl = Tools.BaseUrl + url;
  8989. var aborted = false;
  8990. var fileRequest = {
  8991. onCompleteObservable: new BABYLON.Observable(),
  8992. abort: function () { return aborted = true; },
  8993. };
  8994. var requestFile = function () {
  8995. var request = new XMLHttpRequest();
  8996. var retryHandle = null;
  8997. fileRequest.abort = function () {
  8998. aborted = true;
  8999. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9000. request.abort();
  9001. }
  9002. if (retryHandle !== null) {
  9003. clearTimeout(retryHandle);
  9004. retryHandle = null;
  9005. }
  9006. };
  9007. var retryLoop = function (retryIndex) {
  9008. request.open('GET', loadUrl, true);
  9009. if (useArrayBuffer) {
  9010. request.responseType = "arraybuffer";
  9011. }
  9012. if (onProgress) {
  9013. request.addEventListener("progress", onProgress);
  9014. }
  9015. var onLoadEnd = function () {
  9016. request.removeEventListener("loadend", onLoadEnd);
  9017. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9018. fileRequest.onCompleteObservable.clear();
  9019. };
  9020. request.addEventListener("loadend", onLoadEnd);
  9021. var onReadyStateChange = function () {
  9022. if (aborted) {
  9023. return;
  9024. }
  9025. // In case of undefined state in some browsers.
  9026. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9027. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9028. request.removeEventListener("readystatechange", onReadyStateChange);
  9029. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9030. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9031. return;
  9032. }
  9033. var retryStrategy = Tools.DefaultRetryStrategy;
  9034. if (retryStrategy) {
  9035. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9036. if (waitTime !== -1) {
  9037. // Prevent the request from completing for retry.
  9038. request.removeEventListener("loadend", onLoadEnd);
  9039. request = new XMLHttpRequest();
  9040. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9041. return;
  9042. }
  9043. }
  9044. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9045. if (onError) {
  9046. onError(request, e);
  9047. }
  9048. else {
  9049. throw e;
  9050. }
  9051. }
  9052. };
  9053. request.addEventListener("readystatechange", onReadyStateChange);
  9054. request.send();
  9055. };
  9056. retryLoop(0);
  9057. };
  9058. // Caching all files
  9059. if (database && database.enableSceneOffline) {
  9060. var noIndexedDB_1 = function () {
  9061. if (!aborted) {
  9062. requestFile();
  9063. }
  9064. };
  9065. var loadFromIndexedDB = function () {
  9066. // TODO: database needs to support aborting and should return a IFileRequest
  9067. if (aborted) {
  9068. return;
  9069. }
  9070. if (database) {
  9071. database.loadFileFromDB(url, function (data) {
  9072. if (!aborted) {
  9073. onSuccess(data);
  9074. }
  9075. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9076. }, onProgress ? function (event) {
  9077. if (!aborted) {
  9078. onProgress(event);
  9079. }
  9080. } : undefined, noIndexedDB_1, useArrayBuffer);
  9081. }
  9082. };
  9083. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9084. }
  9085. else {
  9086. requestFile();
  9087. }
  9088. return fileRequest;
  9089. };
  9090. /**
  9091. * Load a script (identified by an url). When the url returns, the
  9092. * content of this file is added into a new script element, attached to the DOM (body element)
  9093. */
  9094. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9095. var head = document.getElementsByTagName('head')[0];
  9096. var script = document.createElement('script');
  9097. script.type = 'text/javascript';
  9098. script.src = scriptUrl;
  9099. script.onload = function () {
  9100. if (onSuccess) {
  9101. onSuccess();
  9102. }
  9103. };
  9104. script.onerror = function (e) {
  9105. if (onError) {
  9106. onError("Unable to load script '" + scriptUrl + "'", e);
  9107. }
  9108. };
  9109. head.appendChild(script);
  9110. };
  9111. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9112. var reader = new FileReader();
  9113. var request = {
  9114. onCompleteObservable: new BABYLON.Observable(),
  9115. abort: function () { return reader.abort(); },
  9116. };
  9117. reader.onloadend = function (e) {
  9118. request.onCompleteObservable.notifyObservers(request);
  9119. };
  9120. reader.onload = function (e) {
  9121. //target doesn't have result from ts 1.3
  9122. callback(e.target['result']);
  9123. };
  9124. reader.onprogress = progressCallback;
  9125. reader.readAsDataURL(fileToLoad);
  9126. return request;
  9127. };
  9128. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9129. var reader = new FileReader();
  9130. var request = {
  9131. onCompleteObservable: new BABYLON.Observable(),
  9132. abort: function () { return reader.abort(); },
  9133. };
  9134. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9135. reader.onerror = function (e) {
  9136. Tools.Log("Error while reading file: " + fileToLoad.name);
  9137. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9138. };
  9139. reader.onload = function (e) {
  9140. //target doesn't have result from ts 1.3
  9141. callback(e.target['result']);
  9142. };
  9143. if (progressCallBack) {
  9144. reader.onprogress = progressCallBack;
  9145. }
  9146. if (!useArrayBuffer) {
  9147. // Asynchronous read
  9148. reader.readAsText(fileToLoad);
  9149. }
  9150. else {
  9151. reader.readAsArrayBuffer(fileToLoad);
  9152. }
  9153. return request;
  9154. };
  9155. //returns a downloadable url to a file content.
  9156. Tools.FileAsURL = function (content) {
  9157. var fileBlob = new Blob([content]);
  9158. var url = window.URL || window.webkitURL;
  9159. var link = url.createObjectURL(fileBlob);
  9160. return link;
  9161. };
  9162. // Misc.
  9163. Tools.Format = function (value, decimals) {
  9164. if (decimals === void 0) { decimals = 2; }
  9165. return value.toFixed(decimals);
  9166. };
  9167. Tools.CheckExtends = function (v, min, max) {
  9168. if (v.x < min.x)
  9169. min.x = v.x;
  9170. if (v.y < min.y)
  9171. min.y = v.y;
  9172. if (v.z < min.z)
  9173. min.z = v.z;
  9174. if (v.x > max.x)
  9175. max.x = v.x;
  9176. if (v.y > max.y)
  9177. max.y = v.y;
  9178. if (v.z > max.z)
  9179. max.z = v.z;
  9180. };
  9181. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9182. for (var prop in source) {
  9183. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9184. continue;
  9185. }
  9186. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9187. continue;
  9188. }
  9189. var sourceValue = source[prop];
  9190. var typeOfSourceValue = typeof sourceValue;
  9191. if (typeOfSourceValue === "function") {
  9192. continue;
  9193. }
  9194. try {
  9195. if (typeOfSourceValue === "object") {
  9196. if (sourceValue instanceof Array) {
  9197. destination[prop] = [];
  9198. if (sourceValue.length > 0) {
  9199. if (typeof sourceValue[0] == "object") {
  9200. for (var index = 0; index < sourceValue.length; index++) {
  9201. var clonedValue = cloneValue(sourceValue[index], destination);
  9202. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9203. destination[prop].push(clonedValue);
  9204. }
  9205. }
  9206. }
  9207. else {
  9208. destination[prop] = sourceValue.slice(0);
  9209. }
  9210. }
  9211. }
  9212. else {
  9213. destination[prop] = cloneValue(sourceValue, destination);
  9214. }
  9215. }
  9216. else {
  9217. destination[prop] = sourceValue;
  9218. }
  9219. }
  9220. catch (e) {
  9221. // Just ignore error (it could be because of a read-only property)
  9222. }
  9223. }
  9224. };
  9225. Tools.IsEmpty = function (obj) {
  9226. for (var i in obj) {
  9227. if (obj.hasOwnProperty(i)) {
  9228. return false;
  9229. }
  9230. }
  9231. return true;
  9232. };
  9233. Tools.RegisterTopRootEvents = function (events) {
  9234. for (var index = 0; index < events.length; index++) {
  9235. var event = events[index];
  9236. window.addEventListener(event.name, event.handler, false);
  9237. try {
  9238. if (window.parent) {
  9239. window.parent.addEventListener(event.name, event.handler, false);
  9240. }
  9241. }
  9242. catch (e) {
  9243. // Silently fails...
  9244. }
  9245. }
  9246. };
  9247. Tools.UnregisterTopRootEvents = function (events) {
  9248. for (var index = 0; index < events.length; index++) {
  9249. var event = events[index];
  9250. window.removeEventListener(event.name, event.handler);
  9251. try {
  9252. if (window.parent) {
  9253. window.parent.removeEventListener(event.name, event.handler);
  9254. }
  9255. }
  9256. catch (e) {
  9257. // Silently fails...
  9258. }
  9259. }
  9260. };
  9261. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9262. if (mimeType === void 0) { mimeType = "image/png"; }
  9263. // Read the contents of the framebuffer
  9264. var numberOfChannelsByLine = width * 4;
  9265. var halfHeight = height / 2;
  9266. //Reading datas from WebGL
  9267. var data = engine.readPixels(0, 0, width, height);
  9268. //To flip image on Y axis.
  9269. for (var i = 0; i < halfHeight; i++) {
  9270. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9271. var currentCell = j + i * numberOfChannelsByLine;
  9272. var targetLine = height - i - 1;
  9273. var targetCell = j + targetLine * numberOfChannelsByLine;
  9274. var temp = data[currentCell];
  9275. data[currentCell] = data[targetCell];
  9276. data[targetCell] = temp;
  9277. }
  9278. }
  9279. // Create a 2D canvas to store the result
  9280. if (!screenshotCanvas) {
  9281. screenshotCanvas = document.createElement('canvas');
  9282. }
  9283. screenshotCanvas.width = width;
  9284. screenshotCanvas.height = height;
  9285. var context = screenshotCanvas.getContext('2d');
  9286. if (context) {
  9287. // Copy the pixels to a 2D canvas
  9288. var imageData = context.createImageData(width, height);
  9289. var castData = (imageData.data);
  9290. castData.set(data);
  9291. context.putImageData(imageData, 0, 0);
  9292. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9293. }
  9294. };
  9295. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9296. if (mimeType === void 0) { mimeType = "image/png"; }
  9297. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9298. if (successCallback) {
  9299. successCallback(base64Image);
  9300. }
  9301. else {
  9302. // We need HTMLCanvasElement.toBlob for HD screenshots
  9303. if (!screenshotCanvas.toBlob) {
  9304. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9305. screenshotCanvas.toBlob = function (callback, type, quality) {
  9306. var _this = this;
  9307. setTimeout(function () {
  9308. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9309. for (var i = 0; i < len; i++) {
  9310. arr[i] = binStr.charCodeAt(i);
  9311. }
  9312. callback(new Blob([arr], { type: type || 'image/png' }));
  9313. });
  9314. };
  9315. }
  9316. screenshotCanvas.toBlob(function (blob) {
  9317. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9318. if (("download" in document.createElement("a"))) {
  9319. if (!fileName) {
  9320. var date = new Date();
  9321. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9322. fileName = "screenshot_" + stringDate + ".png";
  9323. }
  9324. Tools.Download(blob, fileName);
  9325. }
  9326. else {
  9327. var url = URL.createObjectURL(blob);
  9328. var newWindow = window.open("");
  9329. if (!newWindow)
  9330. return;
  9331. var img = newWindow.document.createElement("img");
  9332. img.onload = function () {
  9333. // no longer need to read the blob so it's revoked
  9334. URL.revokeObjectURL(url);
  9335. };
  9336. img.src = url;
  9337. newWindow.document.body.appendChild(img);
  9338. }
  9339. });
  9340. }
  9341. };
  9342. /**
  9343. * Downloads a blob in the browser
  9344. * @param blob defines the blob to download
  9345. * @param fileName defines the name of the downloaded file
  9346. */
  9347. Tools.Download = function (blob, fileName) {
  9348. var url = window.URL.createObjectURL(blob);
  9349. var a = document.createElement("a");
  9350. document.body.appendChild(a);
  9351. a.style.display = "none";
  9352. a.href = url;
  9353. a.download = fileName;
  9354. a.addEventListener("click", function () {
  9355. if (a.parentElement) {
  9356. a.parentElement.removeChild(a);
  9357. }
  9358. });
  9359. a.click();
  9360. window.URL.revokeObjectURL(url);
  9361. };
  9362. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9363. if (mimeType === void 0) { mimeType = "image/png"; }
  9364. var width;
  9365. var height;
  9366. // If a precision value is specified
  9367. if (size.precision) {
  9368. width = Math.round(engine.getRenderWidth() * size.precision);
  9369. height = Math.round(width / engine.getAspectRatio(camera));
  9370. }
  9371. else if (size.width && size.height) {
  9372. width = size.width;
  9373. height = size.height;
  9374. }
  9375. //If passing only width, computing height to keep display canvas ratio.
  9376. else if (size.width && !size.height) {
  9377. width = size.width;
  9378. height = Math.round(width / engine.getAspectRatio(camera));
  9379. }
  9380. //If passing only height, computing width to keep display canvas ratio.
  9381. else if (size.height && !size.width) {
  9382. height = size.height;
  9383. width = Math.round(height * engine.getAspectRatio(camera));
  9384. }
  9385. //Assuming here that "size" parameter is a number
  9386. else if (!isNaN(size)) {
  9387. height = size;
  9388. width = size;
  9389. }
  9390. else {
  9391. Tools.Error("Invalid 'size' parameter !");
  9392. return;
  9393. }
  9394. if (!screenshotCanvas) {
  9395. screenshotCanvas = document.createElement('canvas');
  9396. }
  9397. screenshotCanvas.width = width;
  9398. screenshotCanvas.height = height;
  9399. var renderContext = screenshotCanvas.getContext("2d");
  9400. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9401. var newWidth = width;
  9402. var newHeight = newWidth / ratio;
  9403. if (newHeight > height) {
  9404. newHeight = height;
  9405. newWidth = newHeight * ratio;
  9406. }
  9407. var offsetX = Math.max(0, width - newWidth) / 2;
  9408. var offsetY = Math.max(0, height - newHeight) / 2;
  9409. var renderingCanvas = engine.getRenderingCanvas();
  9410. if (renderContext && renderingCanvas) {
  9411. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9412. }
  9413. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9414. };
  9415. /**
  9416. * Generates an image screenshot from the specified camera.
  9417. *
  9418. * @param engine The engine to use for rendering
  9419. * @param camera The camera to use for rendering
  9420. * @param size This parameter can be set to a single number or to an object with the
  9421. * following (optional) properties: precision, width, height. If a single number is passed,
  9422. * it will be used for both width and height. If an object is passed, the screenshot size
  9423. * will be derived from the parameters. The precision property is a multiplier allowing
  9424. * rendering at a higher or lower resolution.
  9425. * @param successCallback The callback receives a single parameter which contains the
  9426. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9427. * src parameter of an <img> to display it.
  9428. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9429. * Check your browser for supported MIME types.
  9430. * @param samples Texture samples (default: 1)
  9431. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9432. * @param fileName A name for for the downloaded file.
  9433. * @constructor
  9434. */
  9435. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9436. if (mimeType === void 0) { mimeType = "image/png"; }
  9437. if (samples === void 0) { samples = 1; }
  9438. if (antialiasing === void 0) { antialiasing = false; }
  9439. var width;
  9440. var height;
  9441. //If a precision value is specified
  9442. if (size.precision) {
  9443. width = Math.round(engine.getRenderWidth() * size.precision);
  9444. height = Math.round(width / engine.getAspectRatio(camera));
  9445. size = { width: width, height: height };
  9446. }
  9447. else if (size.width && size.height) {
  9448. width = size.width;
  9449. height = size.height;
  9450. }
  9451. //If passing only width, computing height to keep display canvas ratio.
  9452. else if (size.width && !size.height) {
  9453. width = size.width;
  9454. height = Math.round(width / engine.getAspectRatio(camera));
  9455. size = { width: width, height: height };
  9456. }
  9457. //If passing only height, computing width to keep display canvas ratio.
  9458. else if (size.height && !size.width) {
  9459. height = size.height;
  9460. width = Math.round(height * engine.getAspectRatio(camera));
  9461. size = { width: width, height: height };
  9462. }
  9463. //Assuming here that "size" parameter is a number
  9464. else if (!isNaN(size)) {
  9465. height = size;
  9466. width = size;
  9467. }
  9468. else {
  9469. Tools.Error("Invalid 'size' parameter !");
  9470. return;
  9471. }
  9472. var scene = camera.getScene();
  9473. var previousCamera = null;
  9474. if (scene.activeCamera !== camera) {
  9475. previousCamera = scene.activeCamera;
  9476. scene.activeCamera = camera;
  9477. }
  9478. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9479. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9480. texture.renderList = null;
  9481. texture.samples = samples;
  9482. if (antialiasing) {
  9483. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9484. }
  9485. texture.onAfterRenderObservable.add(function () {
  9486. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9487. });
  9488. scene.incrementRenderId();
  9489. scene.resetCachedMaterial();
  9490. texture.render(true);
  9491. texture.dispose();
  9492. if (previousCamera) {
  9493. scene.activeCamera = previousCamera;
  9494. }
  9495. camera.getProjectionMatrix(true); // Force cache refresh;
  9496. };
  9497. // XHR response validator for local file scenario
  9498. Tools.ValidateXHRData = function (xhr, dataType) {
  9499. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9500. if (dataType === void 0) { dataType = 7; }
  9501. try {
  9502. if (dataType & 1) {
  9503. if (xhr.responseText && xhr.responseText.length > 0) {
  9504. return true;
  9505. }
  9506. else if (dataType === 1) {
  9507. return false;
  9508. }
  9509. }
  9510. if (dataType & 2) {
  9511. // Check header width and height since there is no "TGA" magic number
  9512. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9513. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9514. return true;
  9515. }
  9516. else if (dataType === 2) {
  9517. return false;
  9518. }
  9519. }
  9520. if (dataType & 4) {
  9521. // Check for the "DDS" magic number
  9522. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9523. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9524. return true;
  9525. }
  9526. else {
  9527. return false;
  9528. }
  9529. }
  9530. }
  9531. catch (e) {
  9532. // Global protection
  9533. }
  9534. return false;
  9535. };
  9536. /**
  9537. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9538. * Be aware Math.random() could cause collisions, but:
  9539. * "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"
  9540. */
  9541. Tools.RandomId = function () {
  9542. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9543. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9544. return v.toString(16);
  9545. });
  9546. };
  9547. /**
  9548. * Test if the given uri is a base64 string.
  9549. * @param uri The uri to test
  9550. * @return True if the uri is a base64 string or false otherwise.
  9551. */
  9552. Tools.IsBase64 = function (uri) {
  9553. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9554. };
  9555. /**
  9556. * Decode the given base64 uri.
  9557. * @param uri The uri to decode
  9558. * @return The decoded base64 data.
  9559. */
  9560. Tools.DecodeBase64 = function (uri) {
  9561. var decodedString = atob(uri.split(",")[1]);
  9562. var bufferLength = decodedString.length;
  9563. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9564. for (var i = 0; i < bufferLength; i++) {
  9565. bufferView[i] = decodedString.charCodeAt(i);
  9566. }
  9567. return bufferView.buffer;
  9568. };
  9569. Object.defineProperty(Tools, "NoneLogLevel", {
  9570. get: function () {
  9571. return Tools._NoneLogLevel;
  9572. },
  9573. enumerable: true,
  9574. configurable: true
  9575. });
  9576. Object.defineProperty(Tools, "MessageLogLevel", {
  9577. get: function () {
  9578. return Tools._MessageLogLevel;
  9579. },
  9580. enumerable: true,
  9581. configurable: true
  9582. });
  9583. Object.defineProperty(Tools, "WarningLogLevel", {
  9584. get: function () {
  9585. return Tools._WarningLogLevel;
  9586. },
  9587. enumerable: true,
  9588. configurable: true
  9589. });
  9590. Object.defineProperty(Tools, "ErrorLogLevel", {
  9591. get: function () {
  9592. return Tools._ErrorLogLevel;
  9593. },
  9594. enumerable: true,
  9595. configurable: true
  9596. });
  9597. Object.defineProperty(Tools, "AllLogLevel", {
  9598. get: function () {
  9599. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9600. },
  9601. enumerable: true,
  9602. configurable: true
  9603. });
  9604. Tools._AddLogEntry = function (entry) {
  9605. Tools._LogCache = entry + Tools._LogCache;
  9606. if (Tools.OnNewCacheEntry) {
  9607. Tools.OnNewCacheEntry(entry);
  9608. }
  9609. };
  9610. Tools._FormatMessage = function (message) {
  9611. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9612. var date = new Date();
  9613. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9614. };
  9615. Tools._LogDisabled = function (message) {
  9616. // nothing to do
  9617. };
  9618. Tools._LogEnabled = function (message) {
  9619. var formattedMessage = Tools._FormatMessage(message);
  9620. console.log("BJS - " + formattedMessage);
  9621. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9622. Tools._AddLogEntry(entry);
  9623. };
  9624. Tools._WarnDisabled = function (message) {
  9625. // nothing to do
  9626. };
  9627. Tools._WarnEnabled = function (message) {
  9628. var formattedMessage = Tools._FormatMessage(message);
  9629. console.warn("BJS - " + formattedMessage);
  9630. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9631. Tools._AddLogEntry(entry);
  9632. };
  9633. Tools._ErrorDisabled = function (message) {
  9634. // nothing to do
  9635. };
  9636. Tools._ErrorEnabled = function (message) {
  9637. Tools.errorsCount++;
  9638. var formattedMessage = Tools._FormatMessage(message);
  9639. console.error("BJS - " + formattedMessage);
  9640. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9641. Tools._AddLogEntry(entry);
  9642. };
  9643. Object.defineProperty(Tools, "LogCache", {
  9644. get: function () {
  9645. return Tools._LogCache;
  9646. },
  9647. enumerable: true,
  9648. configurable: true
  9649. });
  9650. Tools.ClearLogCache = function () {
  9651. Tools._LogCache = "";
  9652. Tools.errorsCount = 0;
  9653. };
  9654. Object.defineProperty(Tools, "LogLevels", {
  9655. set: function (level) {
  9656. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9657. Tools.Log = Tools._LogEnabled;
  9658. }
  9659. else {
  9660. Tools.Log = Tools._LogDisabled;
  9661. }
  9662. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9663. Tools.Warn = Tools._WarnEnabled;
  9664. }
  9665. else {
  9666. Tools.Warn = Tools._WarnDisabled;
  9667. }
  9668. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9669. Tools.Error = Tools._ErrorEnabled;
  9670. }
  9671. else {
  9672. Tools.Error = Tools._ErrorDisabled;
  9673. }
  9674. },
  9675. enumerable: true,
  9676. configurable: true
  9677. });
  9678. Tools.IsWindowObjectExist = function () {
  9679. return (typeof window) !== "undefined";
  9680. };
  9681. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9682. get: function () {
  9683. return Tools._PerformanceNoneLogLevel;
  9684. },
  9685. enumerable: true,
  9686. configurable: true
  9687. });
  9688. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9689. get: function () {
  9690. return Tools._PerformanceUserMarkLogLevel;
  9691. },
  9692. enumerable: true,
  9693. configurable: true
  9694. });
  9695. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9696. get: function () {
  9697. return Tools._PerformanceConsoleLogLevel;
  9698. },
  9699. enumerable: true,
  9700. configurable: true
  9701. });
  9702. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9703. set: function (level) {
  9704. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9705. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9706. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9707. return;
  9708. }
  9709. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9710. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9711. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9712. return;
  9713. }
  9714. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9715. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9716. },
  9717. enumerable: true,
  9718. configurable: true
  9719. });
  9720. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9721. };
  9722. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9723. };
  9724. Tools._StartUserMark = function (counterName, condition) {
  9725. if (condition === void 0) { condition = true; }
  9726. if (!Tools._performance) {
  9727. if (!Tools.IsWindowObjectExist()) {
  9728. return;
  9729. }
  9730. Tools._performance = window.performance;
  9731. }
  9732. if (!condition || !Tools._performance.mark) {
  9733. return;
  9734. }
  9735. Tools._performance.mark(counterName + "-Begin");
  9736. };
  9737. Tools._EndUserMark = function (counterName, condition) {
  9738. if (condition === void 0) { condition = true; }
  9739. if (!condition || !Tools._performance.mark) {
  9740. return;
  9741. }
  9742. Tools._performance.mark(counterName + "-End");
  9743. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9744. };
  9745. Tools._StartPerformanceConsole = function (counterName, condition) {
  9746. if (condition === void 0) { condition = true; }
  9747. if (!condition) {
  9748. return;
  9749. }
  9750. Tools._StartUserMark(counterName, condition);
  9751. if (console.time) {
  9752. console.time(counterName);
  9753. }
  9754. };
  9755. Tools._EndPerformanceConsole = function (counterName, condition) {
  9756. if (condition === void 0) { condition = true; }
  9757. if (!condition) {
  9758. return;
  9759. }
  9760. Tools._EndUserMark(counterName, condition);
  9761. if (console.time) {
  9762. console.timeEnd(counterName);
  9763. }
  9764. };
  9765. Object.defineProperty(Tools, "Now", {
  9766. get: function () {
  9767. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9768. return window.performance.now();
  9769. }
  9770. return Date.now();
  9771. },
  9772. enumerable: true,
  9773. configurable: true
  9774. });
  9775. /**
  9776. * This method will return the name of the class used to create the instance of the given object.
  9777. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9778. * @param object the object to get the class name from
  9779. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9780. */
  9781. Tools.GetClassName = function (object, isType) {
  9782. if (isType === void 0) { isType = false; }
  9783. var name = null;
  9784. if (!isType && object.getClassName) {
  9785. name = object.getClassName();
  9786. }
  9787. else {
  9788. if (object instanceof Object) {
  9789. var classObj = isType ? object : Object.getPrototypeOf(object);
  9790. name = classObj.constructor["__bjsclassName__"];
  9791. }
  9792. if (!name) {
  9793. name = typeof object;
  9794. }
  9795. }
  9796. return name;
  9797. };
  9798. Tools.First = function (array, predicate) {
  9799. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9800. var el = array_1[_i];
  9801. if (predicate(el)) {
  9802. return el;
  9803. }
  9804. }
  9805. return null;
  9806. };
  9807. /**
  9808. * This method will return the name of the full name of the class, including its owning module (if any).
  9809. * 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).
  9810. * @param object the object to get the class name from
  9811. * @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.
  9812. */
  9813. Tools.getFullClassName = function (object, isType) {
  9814. if (isType === void 0) { isType = false; }
  9815. var className = null;
  9816. var moduleName = null;
  9817. if (!isType && object.getClassName) {
  9818. className = object.getClassName();
  9819. }
  9820. else {
  9821. if (object instanceof Object) {
  9822. var classObj = isType ? object : Object.getPrototypeOf(object);
  9823. className = classObj.constructor["__bjsclassName__"];
  9824. moduleName = classObj.constructor["__bjsmoduleName__"];
  9825. }
  9826. if (!className) {
  9827. className = typeof object;
  9828. }
  9829. }
  9830. if (!className) {
  9831. return null;
  9832. }
  9833. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9834. };
  9835. /**
  9836. * 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.
  9837. * @param array
  9838. */
  9839. Tools.arrayOrStringFeeder = function (array) {
  9840. return function (index) {
  9841. if (index >= array.length) {
  9842. return null;
  9843. }
  9844. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9845. if (val && val.getHashCode) {
  9846. val = val.getHashCode();
  9847. }
  9848. if (typeof val === "string") {
  9849. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9850. }
  9851. return val;
  9852. };
  9853. };
  9854. /**
  9855. * Compute the hashCode of a stream of number
  9856. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9857. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9858. * @return the hash code computed
  9859. */
  9860. Tools.hashCodeFromStream = function (feeder) {
  9861. // Based from here: http://stackoverflow.com/a/7616484/802124
  9862. var hash = 0;
  9863. var index = 0;
  9864. var chr = feeder(index++);
  9865. while (chr != null) {
  9866. hash = ((hash << 5) - hash) + chr;
  9867. hash |= 0; // Convert to 32bit integer
  9868. chr = feeder(index++);
  9869. }
  9870. return hash;
  9871. };
  9872. /**
  9873. * Returns a promise that resolves after the given amount of time.
  9874. * @param delay Number of milliseconds to delay
  9875. * @returns Promise that resolves after the given amount of time
  9876. */
  9877. Tools.DelayAsync = function (delay) {
  9878. return new Promise(function (resolve) {
  9879. setTimeout(function () {
  9880. resolve();
  9881. }, delay);
  9882. });
  9883. };
  9884. /**
  9885. * Gets the current gradient from an array of IValueGradient
  9886. * @param ratio defines the current ratio to get
  9887. * @param gradients defines the array of IValueGradient
  9888. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  9889. */
  9890. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  9891. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  9892. var currentGradient = gradients[gradientIndex];
  9893. var nextGradient = gradients[gradientIndex + 1];
  9894. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  9895. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  9896. updateFunc(currentGradient, nextGradient, scale);
  9897. }
  9898. }
  9899. };
  9900. Tools.BaseUrl = "";
  9901. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9902. /**
  9903. * Default behaviour for cors in the application.
  9904. * It can be a string if the expected behavior is identical in the entire app.
  9905. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9906. */
  9907. Tools.CorsBehavior = "anonymous";
  9908. Tools.UseFallbackTexture = true;
  9909. /**
  9910. * Use this object to register external classes like custom textures or material
  9911. * to allow the laoders to instantiate them
  9912. */
  9913. Tools.RegisteredExternalClasses = {};
  9914. // Used in case of a texture loading problem
  9915. 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";
  9916. Tools._tmpFloatArray = new Float32Array(1);
  9917. Tools.PreprocessUrl = function (url) {
  9918. return url;
  9919. };
  9920. // Logs
  9921. Tools._NoneLogLevel = 0;
  9922. Tools._MessageLogLevel = 1;
  9923. Tools._WarningLogLevel = 2;
  9924. Tools._ErrorLogLevel = 4;
  9925. Tools._LogCache = "";
  9926. Tools.errorsCount = 0;
  9927. Tools.Log = Tools._LogEnabled;
  9928. Tools.Warn = Tools._WarnEnabled;
  9929. Tools.Error = Tools._ErrorEnabled;
  9930. // Performances
  9931. Tools._PerformanceNoneLogLevel = 0;
  9932. Tools._PerformanceUserMarkLogLevel = 1;
  9933. Tools._PerformanceConsoleLogLevel = 2;
  9934. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9935. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9936. return Tools;
  9937. }());
  9938. BABYLON.Tools = Tools;
  9939. /**
  9940. * This class is used to track a performance counter which is number based.
  9941. * The user has access to many properties which give statistics of different nature
  9942. *
  9943. * The implementer can track two kinds of Performance Counter: time and count
  9944. * 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.
  9945. * 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.
  9946. */
  9947. var PerfCounter = /** @class */ (function () {
  9948. function PerfCounter() {
  9949. this._startMonitoringTime = 0;
  9950. this._min = 0;
  9951. this._max = 0;
  9952. this._average = 0;
  9953. this._lastSecAverage = 0;
  9954. this._current = 0;
  9955. this._totalValueCount = 0;
  9956. this._totalAccumulated = 0;
  9957. this._lastSecAccumulated = 0;
  9958. this._lastSecTime = 0;
  9959. this._lastSecValueCount = 0;
  9960. }
  9961. Object.defineProperty(PerfCounter.prototype, "min", {
  9962. /**
  9963. * Returns the smallest value ever
  9964. */
  9965. get: function () {
  9966. return this._min;
  9967. },
  9968. enumerable: true,
  9969. configurable: true
  9970. });
  9971. Object.defineProperty(PerfCounter.prototype, "max", {
  9972. /**
  9973. * Returns the biggest value ever
  9974. */
  9975. get: function () {
  9976. return this._max;
  9977. },
  9978. enumerable: true,
  9979. configurable: true
  9980. });
  9981. Object.defineProperty(PerfCounter.prototype, "average", {
  9982. /**
  9983. * Returns the average value since the performance counter is running
  9984. */
  9985. get: function () {
  9986. return this._average;
  9987. },
  9988. enumerable: true,
  9989. configurable: true
  9990. });
  9991. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9992. /**
  9993. * Returns the average value of the last second the counter was monitored
  9994. */
  9995. get: function () {
  9996. return this._lastSecAverage;
  9997. },
  9998. enumerable: true,
  9999. configurable: true
  10000. });
  10001. Object.defineProperty(PerfCounter.prototype, "current", {
  10002. /**
  10003. * Returns the current value
  10004. */
  10005. get: function () {
  10006. return this._current;
  10007. },
  10008. enumerable: true,
  10009. configurable: true
  10010. });
  10011. Object.defineProperty(PerfCounter.prototype, "total", {
  10012. get: function () {
  10013. return this._totalAccumulated;
  10014. },
  10015. enumerable: true,
  10016. configurable: true
  10017. });
  10018. Object.defineProperty(PerfCounter.prototype, "count", {
  10019. get: function () {
  10020. return this._totalValueCount;
  10021. },
  10022. enumerable: true,
  10023. configurable: true
  10024. });
  10025. /**
  10026. * Call this method to start monitoring a new frame.
  10027. * 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.
  10028. */
  10029. PerfCounter.prototype.fetchNewFrame = function () {
  10030. this._totalValueCount++;
  10031. this._current = 0;
  10032. this._lastSecValueCount++;
  10033. };
  10034. /**
  10035. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10036. * @param newCount the count value to add to the monitored count
  10037. * @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.
  10038. */
  10039. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10040. if (!PerfCounter.Enabled) {
  10041. return;
  10042. }
  10043. this._current += newCount;
  10044. if (fetchResult) {
  10045. this._fetchResult();
  10046. }
  10047. };
  10048. /**
  10049. * Start monitoring this performance counter
  10050. */
  10051. PerfCounter.prototype.beginMonitoring = function () {
  10052. if (!PerfCounter.Enabled) {
  10053. return;
  10054. }
  10055. this._startMonitoringTime = Tools.Now;
  10056. };
  10057. /**
  10058. * Compute the time lapsed since the previous beginMonitoring() call.
  10059. * @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
  10060. */
  10061. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10062. if (newFrame === void 0) { newFrame = true; }
  10063. if (!PerfCounter.Enabled) {
  10064. return;
  10065. }
  10066. if (newFrame) {
  10067. this.fetchNewFrame();
  10068. }
  10069. var currentTime = Tools.Now;
  10070. this._current = currentTime - this._startMonitoringTime;
  10071. if (newFrame) {
  10072. this._fetchResult();
  10073. }
  10074. };
  10075. PerfCounter.prototype._fetchResult = function () {
  10076. this._totalAccumulated += this._current;
  10077. this._lastSecAccumulated += this._current;
  10078. // Min/Max update
  10079. this._min = Math.min(this._min, this._current);
  10080. this._max = Math.max(this._max, this._current);
  10081. this._average = this._totalAccumulated / this._totalValueCount;
  10082. // Reset last sec?
  10083. var now = Tools.Now;
  10084. if ((now - this._lastSecTime) > 1000) {
  10085. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10086. this._lastSecTime = now;
  10087. this._lastSecAccumulated = 0;
  10088. this._lastSecValueCount = 0;
  10089. }
  10090. };
  10091. PerfCounter.Enabled = true;
  10092. return PerfCounter;
  10093. }());
  10094. BABYLON.PerfCounter = PerfCounter;
  10095. /**
  10096. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10097. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10098. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10099. * @param name The name of the class, case should be preserved
  10100. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10101. */
  10102. function className(name, module) {
  10103. return function (target) {
  10104. target["__bjsclassName__"] = name;
  10105. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10106. };
  10107. }
  10108. BABYLON.className = className;
  10109. /**
  10110. * An implementation of a loop for asynchronous functions.
  10111. */
  10112. var AsyncLoop = /** @class */ (function () {
  10113. /**
  10114. * Constroctor.
  10115. * @param iterations the number of iterations.
  10116. * @param _fn the function to run each iteration
  10117. * @param _successCallback the callback that will be called upon succesful execution
  10118. * @param offset starting offset.
  10119. */
  10120. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10121. if (offset === void 0) { offset = 0; }
  10122. this.iterations = iterations;
  10123. this._fn = _fn;
  10124. this._successCallback = _successCallback;
  10125. this.index = offset - 1;
  10126. this._done = false;
  10127. }
  10128. /**
  10129. * Execute the next iteration. Must be called after the last iteration was finished.
  10130. */
  10131. AsyncLoop.prototype.executeNext = function () {
  10132. if (!this._done) {
  10133. if (this.index + 1 < this.iterations) {
  10134. ++this.index;
  10135. this._fn(this);
  10136. }
  10137. else {
  10138. this.breakLoop();
  10139. }
  10140. }
  10141. };
  10142. /**
  10143. * Break the loop and run the success callback.
  10144. */
  10145. AsyncLoop.prototype.breakLoop = function () {
  10146. this._done = true;
  10147. this._successCallback();
  10148. };
  10149. /**
  10150. * Helper function
  10151. */
  10152. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10153. if (offset === void 0) { offset = 0; }
  10154. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10155. loop.executeNext();
  10156. return loop;
  10157. };
  10158. /**
  10159. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10160. * @param iterations total number of iterations
  10161. * @param syncedIterations number of synchronous iterations in each async iteration.
  10162. * @param fn the function to call each iteration.
  10163. * @param callback a success call back that will be called when iterating stops.
  10164. * @param breakFunction a break condition (optional)
  10165. * @param timeout timeout settings for the setTimeout function. default - 0.
  10166. * @constructor
  10167. */
  10168. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10169. if (timeout === void 0) { timeout = 0; }
  10170. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10171. if (breakFunction && breakFunction())
  10172. loop.breakLoop();
  10173. else {
  10174. setTimeout(function () {
  10175. for (var i = 0; i < syncedIterations; ++i) {
  10176. var iteration = (loop.index * syncedIterations) + i;
  10177. if (iteration >= iterations)
  10178. break;
  10179. fn(iteration);
  10180. if (breakFunction && breakFunction()) {
  10181. loop.breakLoop();
  10182. break;
  10183. }
  10184. }
  10185. loop.executeNext();
  10186. }, timeout);
  10187. }
  10188. }, callback);
  10189. };
  10190. return AsyncLoop;
  10191. }());
  10192. BABYLON.AsyncLoop = AsyncLoop;
  10193. })(BABYLON || (BABYLON = {}));
  10194. //# sourceMappingURL=babylon.tools.js.map
  10195. var BABYLON;
  10196. (function (BABYLON) {
  10197. var PromiseStates;
  10198. (function (PromiseStates) {
  10199. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10200. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10201. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10202. })(PromiseStates || (PromiseStates = {}));
  10203. var FulFillmentAgregator = /** @class */ (function () {
  10204. function FulFillmentAgregator() {
  10205. this.count = 0;
  10206. this.target = 0;
  10207. this.results = [];
  10208. }
  10209. return FulFillmentAgregator;
  10210. }());
  10211. var InternalPromise = /** @class */ (function () {
  10212. function InternalPromise(resolver) {
  10213. var _this = this;
  10214. this._state = PromiseStates.Pending;
  10215. this._children = new Array();
  10216. this._rejectWasConsumed = false;
  10217. if (!resolver) {
  10218. return;
  10219. }
  10220. try {
  10221. resolver(function (value) {
  10222. _this._resolve(value);
  10223. }, function (reason) {
  10224. _this._reject(reason);
  10225. });
  10226. }
  10227. catch (e) {
  10228. this._reject(e);
  10229. }
  10230. }
  10231. Object.defineProperty(InternalPromise.prototype, "_result", {
  10232. get: function () {
  10233. return this._resultValue;
  10234. },
  10235. set: function (value) {
  10236. this._resultValue = value;
  10237. if (this._parent && this._parent._result === undefined) {
  10238. this._parent._result = value;
  10239. }
  10240. },
  10241. enumerable: true,
  10242. configurable: true
  10243. });
  10244. InternalPromise.prototype.catch = function (onRejected) {
  10245. return this.then(undefined, onRejected);
  10246. };
  10247. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10248. var _this = this;
  10249. var newPromise = new InternalPromise();
  10250. newPromise._onFulfilled = onFulfilled;
  10251. newPromise._onRejected = onRejected;
  10252. // Composition
  10253. this._children.push(newPromise);
  10254. newPromise._parent = this;
  10255. if (this._state !== PromiseStates.Pending) {
  10256. BABYLON.Tools.SetImmediate(function () {
  10257. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10258. var returnedValue = newPromise._resolve(_this._result);
  10259. if (returnedValue !== undefined && returnedValue !== null) {
  10260. if (returnedValue._state !== undefined) {
  10261. var returnedPromise = returnedValue;
  10262. newPromise._children.push(returnedPromise);
  10263. returnedPromise._parent = newPromise;
  10264. newPromise = returnedPromise;
  10265. }
  10266. else {
  10267. newPromise._result = returnedValue;
  10268. }
  10269. }
  10270. }
  10271. else {
  10272. newPromise._reject(_this._reason);
  10273. }
  10274. });
  10275. }
  10276. return newPromise;
  10277. };
  10278. InternalPromise.prototype._moveChildren = function (children) {
  10279. var _this = this;
  10280. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10281. this._children.forEach(function (child) {
  10282. child._parent = _this;
  10283. });
  10284. if (this._state === PromiseStates.Fulfilled) {
  10285. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10286. var child = _b[_i];
  10287. child._resolve(this._result);
  10288. }
  10289. }
  10290. else if (this._state === PromiseStates.Rejected) {
  10291. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10292. var child = _d[_c];
  10293. child._reject(this._reason);
  10294. }
  10295. }
  10296. var _a;
  10297. };
  10298. InternalPromise.prototype._resolve = function (value) {
  10299. try {
  10300. this._state = PromiseStates.Fulfilled;
  10301. var returnedValue = null;
  10302. if (this._onFulfilled) {
  10303. returnedValue = this._onFulfilled(value);
  10304. }
  10305. if (returnedValue !== undefined && returnedValue !== null) {
  10306. if (returnedValue._state !== undefined) {
  10307. // Transmit children
  10308. var returnedPromise = returnedValue;
  10309. returnedPromise._parent = this;
  10310. returnedPromise._moveChildren(this._children);
  10311. value = returnedPromise._result;
  10312. }
  10313. else {
  10314. value = returnedValue;
  10315. }
  10316. }
  10317. this._result = value;
  10318. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10319. var child = _a[_i];
  10320. child._resolve(value);
  10321. }
  10322. this._children.length = 0;
  10323. delete this._onFulfilled;
  10324. delete this._onRejected;
  10325. }
  10326. catch (e) {
  10327. this._reject(e, true);
  10328. }
  10329. };
  10330. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10331. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10332. this._state = PromiseStates.Rejected;
  10333. this._reason = reason;
  10334. if (this._onRejected && !onLocalThrow) {
  10335. try {
  10336. this._onRejected(reason);
  10337. this._rejectWasConsumed = true;
  10338. }
  10339. catch (e) {
  10340. reason = e;
  10341. }
  10342. }
  10343. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10344. var child = _a[_i];
  10345. if (this._rejectWasConsumed) {
  10346. child._resolve(null);
  10347. }
  10348. else {
  10349. child._reject(reason);
  10350. }
  10351. }
  10352. this._children.length = 0;
  10353. delete this._onFulfilled;
  10354. delete this._onRejected;
  10355. };
  10356. InternalPromise.resolve = function (value) {
  10357. var newPromise = new InternalPromise();
  10358. newPromise._resolve(value);
  10359. return newPromise;
  10360. };
  10361. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10362. promise.then(function (value) {
  10363. agregator.results[index] = value;
  10364. agregator.count++;
  10365. if (agregator.count === agregator.target) {
  10366. agregator.rootPromise._resolve(agregator.results);
  10367. }
  10368. return null;
  10369. }, function (reason) {
  10370. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10371. agregator.rootPromise._reject(reason);
  10372. }
  10373. });
  10374. };
  10375. InternalPromise.all = function (promises) {
  10376. var newPromise = new InternalPromise();
  10377. var agregator = new FulFillmentAgregator();
  10378. agregator.target = promises.length;
  10379. agregator.rootPromise = newPromise;
  10380. if (promises.length) {
  10381. for (var index = 0; index < promises.length; index++) {
  10382. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10383. }
  10384. }
  10385. else {
  10386. newPromise._resolve([]);
  10387. }
  10388. return newPromise;
  10389. };
  10390. InternalPromise.race = function (promises) {
  10391. var newPromise = new InternalPromise();
  10392. if (promises.length) {
  10393. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10394. var promise = promises_1[_i];
  10395. promise.then(function (value) {
  10396. if (newPromise) {
  10397. newPromise._resolve(value);
  10398. newPromise = null;
  10399. }
  10400. return null;
  10401. }, function (reason) {
  10402. if (newPromise) {
  10403. newPromise._reject(reason);
  10404. newPromise = null;
  10405. }
  10406. });
  10407. }
  10408. }
  10409. return newPromise;
  10410. };
  10411. return InternalPromise;
  10412. }());
  10413. /**
  10414. * Helper class that provides a small promise polyfill
  10415. */
  10416. var PromisePolyfill = /** @class */ (function () {
  10417. function PromisePolyfill() {
  10418. }
  10419. /**
  10420. * Static function used to check if the polyfill is required
  10421. * If this is the case then the function will inject the polyfill to window.Promise
  10422. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10423. */
  10424. PromisePolyfill.Apply = function (force) {
  10425. if (force === void 0) { force = false; }
  10426. if (force || typeof Promise === 'undefined') {
  10427. var root = window;
  10428. root.Promise = InternalPromise;
  10429. }
  10430. };
  10431. return PromisePolyfill;
  10432. }());
  10433. BABYLON.PromisePolyfill = PromisePolyfill;
  10434. })(BABYLON || (BABYLON = {}));
  10435. //# sourceMappingURL=babylon.promise.js.map
  10436. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10437. var BABYLON;
  10438. (function (BABYLON) {
  10439. /**
  10440. * Helper class to push actions to a pool of workers.
  10441. */
  10442. var WorkerPool = /** @class */ (function () {
  10443. /**
  10444. * Constructor
  10445. * @param workers Array of workers to use for actions
  10446. */
  10447. function WorkerPool(workers) {
  10448. this._pendingActions = new Array();
  10449. this._workerInfos = workers.map(function (worker) { return ({
  10450. worker: worker,
  10451. active: false
  10452. }); });
  10453. }
  10454. /**
  10455. * Terminates all workers and clears any pending actions.
  10456. */
  10457. WorkerPool.prototype.dispose = function () {
  10458. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10459. var workerInfo = _a[_i];
  10460. workerInfo.worker.terminate();
  10461. }
  10462. delete this._workerInfos;
  10463. delete this._pendingActions;
  10464. };
  10465. /**
  10466. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10467. * pended until a worker has completed its action.
  10468. * @param action The action to perform. Call onComplete when the action is complete.
  10469. */
  10470. WorkerPool.prototype.push = function (action) {
  10471. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10472. var workerInfo = _a[_i];
  10473. if (!workerInfo.active) {
  10474. this._execute(workerInfo, action);
  10475. return;
  10476. }
  10477. }
  10478. this._pendingActions.push(action);
  10479. };
  10480. WorkerPool.prototype._execute = function (workerInfo, action) {
  10481. var _this = this;
  10482. workerInfo.active = true;
  10483. action(workerInfo.worker, function () {
  10484. workerInfo.active = false;
  10485. var nextAction = _this._pendingActions.shift();
  10486. if (nextAction) {
  10487. _this._execute(workerInfo, nextAction);
  10488. }
  10489. });
  10490. };
  10491. return WorkerPool;
  10492. }());
  10493. BABYLON.WorkerPool = WorkerPool;
  10494. })(BABYLON || (BABYLON = {}));
  10495. //# sourceMappingURL=babylon.workerPool.js.map
  10496. var BABYLON;
  10497. (function (BABYLON) {
  10498. /**
  10499. * @hidden
  10500. **/
  10501. var _AlphaState = /** @class */ (function () {
  10502. /**
  10503. * Initializes the state.
  10504. */
  10505. function _AlphaState() {
  10506. this._isAlphaBlendDirty = false;
  10507. this._isBlendFunctionParametersDirty = false;
  10508. this._isBlendEquationParametersDirty = false;
  10509. this._isBlendConstantsDirty = false;
  10510. this._alphaBlend = false;
  10511. this._blendFunctionParameters = new Array(4);
  10512. this._blendEquationParameters = new Array(2);
  10513. this._blendConstants = new Array(4);
  10514. this.reset();
  10515. }
  10516. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10517. get: function () {
  10518. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10519. },
  10520. enumerable: true,
  10521. configurable: true
  10522. });
  10523. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10524. get: function () {
  10525. return this._alphaBlend;
  10526. },
  10527. set: function (value) {
  10528. if (this._alphaBlend === value) {
  10529. return;
  10530. }
  10531. this._alphaBlend = value;
  10532. this._isAlphaBlendDirty = true;
  10533. },
  10534. enumerable: true,
  10535. configurable: true
  10536. });
  10537. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10538. if (this._blendConstants[0] === r &&
  10539. this._blendConstants[1] === g &&
  10540. this._blendConstants[2] === b &&
  10541. this._blendConstants[3] === a) {
  10542. return;
  10543. }
  10544. this._blendConstants[0] = r;
  10545. this._blendConstants[1] = g;
  10546. this._blendConstants[2] = b;
  10547. this._blendConstants[3] = a;
  10548. this._isBlendConstantsDirty = true;
  10549. };
  10550. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10551. if (this._blendFunctionParameters[0] === value0 &&
  10552. this._blendFunctionParameters[1] === value1 &&
  10553. this._blendFunctionParameters[2] === value2 &&
  10554. this._blendFunctionParameters[3] === value3) {
  10555. return;
  10556. }
  10557. this._blendFunctionParameters[0] = value0;
  10558. this._blendFunctionParameters[1] = value1;
  10559. this._blendFunctionParameters[2] = value2;
  10560. this._blendFunctionParameters[3] = value3;
  10561. this._isBlendFunctionParametersDirty = true;
  10562. };
  10563. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10564. if (this._blendEquationParameters[0] === rgb &&
  10565. this._blendEquationParameters[1] === alpha) {
  10566. return;
  10567. }
  10568. this._blendEquationParameters[0] = rgb;
  10569. this._blendEquationParameters[1] = alpha;
  10570. this._isBlendEquationParametersDirty = true;
  10571. };
  10572. _AlphaState.prototype.reset = function () {
  10573. this._alphaBlend = false;
  10574. this._blendFunctionParameters[0] = null;
  10575. this._blendFunctionParameters[1] = null;
  10576. this._blendFunctionParameters[2] = null;
  10577. this._blendFunctionParameters[3] = null;
  10578. this._blendEquationParameters[0] = null;
  10579. this._blendEquationParameters[1] = null;
  10580. this._blendConstants[0] = null;
  10581. this._blendConstants[1] = null;
  10582. this._blendConstants[2] = null;
  10583. this._blendConstants[3] = null;
  10584. this._isAlphaBlendDirty = true;
  10585. this._isBlendFunctionParametersDirty = false;
  10586. this._isBlendEquationParametersDirty = false;
  10587. this._isBlendConstantsDirty = false;
  10588. };
  10589. _AlphaState.prototype.apply = function (gl) {
  10590. if (!this.isDirty) {
  10591. return;
  10592. }
  10593. // Alpha blend
  10594. if (this._isAlphaBlendDirty) {
  10595. if (this._alphaBlend) {
  10596. gl.enable(gl.BLEND);
  10597. }
  10598. else {
  10599. gl.disable(gl.BLEND);
  10600. }
  10601. this._isAlphaBlendDirty = false;
  10602. }
  10603. // Alpha function
  10604. if (this._isBlendFunctionParametersDirty) {
  10605. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10606. this._isBlendFunctionParametersDirty = false;
  10607. }
  10608. // Alpha equation
  10609. if (this._isBlendEquationParametersDirty) {
  10610. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10611. this._isBlendEquationParametersDirty = false;
  10612. }
  10613. // Constants
  10614. if (this._isBlendConstantsDirty) {
  10615. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10616. this._isBlendConstantsDirty = false;
  10617. }
  10618. };
  10619. return _AlphaState;
  10620. }());
  10621. BABYLON._AlphaState = _AlphaState;
  10622. })(BABYLON || (BABYLON = {}));
  10623. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10624. var BABYLON;
  10625. (function (BABYLON) {
  10626. /**
  10627. * @hidden
  10628. **/
  10629. var _DepthCullingState = /** @class */ (function () {
  10630. /**
  10631. * Initializes the state.
  10632. */
  10633. function _DepthCullingState() {
  10634. this._isDepthTestDirty = false;
  10635. this._isDepthMaskDirty = false;
  10636. this._isDepthFuncDirty = false;
  10637. this._isCullFaceDirty = false;
  10638. this._isCullDirty = false;
  10639. this._isZOffsetDirty = false;
  10640. this._isFrontFaceDirty = false;
  10641. this.reset();
  10642. }
  10643. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10644. get: function () {
  10645. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10646. },
  10647. enumerable: true,
  10648. configurable: true
  10649. });
  10650. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10651. get: function () {
  10652. return this._zOffset;
  10653. },
  10654. set: function (value) {
  10655. if (this._zOffset === value) {
  10656. return;
  10657. }
  10658. this._zOffset = value;
  10659. this._isZOffsetDirty = true;
  10660. },
  10661. enumerable: true,
  10662. configurable: true
  10663. });
  10664. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10665. get: function () {
  10666. return this._cullFace;
  10667. },
  10668. set: function (value) {
  10669. if (this._cullFace === value) {
  10670. return;
  10671. }
  10672. this._cullFace = value;
  10673. this._isCullFaceDirty = true;
  10674. },
  10675. enumerable: true,
  10676. configurable: true
  10677. });
  10678. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10679. get: function () {
  10680. return this._cull;
  10681. },
  10682. set: function (value) {
  10683. if (this._cull === value) {
  10684. return;
  10685. }
  10686. this._cull = value;
  10687. this._isCullDirty = true;
  10688. },
  10689. enumerable: true,
  10690. configurable: true
  10691. });
  10692. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10693. get: function () {
  10694. return this._depthFunc;
  10695. },
  10696. set: function (value) {
  10697. if (this._depthFunc === value) {
  10698. return;
  10699. }
  10700. this._depthFunc = value;
  10701. this._isDepthFuncDirty = true;
  10702. },
  10703. enumerable: true,
  10704. configurable: true
  10705. });
  10706. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10707. get: function () {
  10708. return this._depthMask;
  10709. },
  10710. set: function (value) {
  10711. if (this._depthMask === value) {
  10712. return;
  10713. }
  10714. this._depthMask = value;
  10715. this._isDepthMaskDirty = true;
  10716. },
  10717. enumerable: true,
  10718. configurable: true
  10719. });
  10720. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10721. get: function () {
  10722. return this._depthTest;
  10723. },
  10724. set: function (value) {
  10725. if (this._depthTest === value) {
  10726. return;
  10727. }
  10728. this._depthTest = value;
  10729. this._isDepthTestDirty = true;
  10730. },
  10731. enumerable: true,
  10732. configurable: true
  10733. });
  10734. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10735. get: function () {
  10736. return this._frontFace;
  10737. },
  10738. set: function (value) {
  10739. if (this._frontFace === value) {
  10740. return;
  10741. }
  10742. this._frontFace = value;
  10743. this._isFrontFaceDirty = true;
  10744. },
  10745. enumerable: true,
  10746. configurable: true
  10747. });
  10748. _DepthCullingState.prototype.reset = function () {
  10749. this._depthMask = true;
  10750. this._depthTest = true;
  10751. this._depthFunc = null;
  10752. this._cullFace = null;
  10753. this._cull = null;
  10754. this._zOffset = 0;
  10755. this._frontFace = null;
  10756. this._isDepthTestDirty = true;
  10757. this._isDepthMaskDirty = true;
  10758. this._isDepthFuncDirty = false;
  10759. this._isCullFaceDirty = false;
  10760. this._isCullDirty = false;
  10761. this._isZOffsetDirty = false;
  10762. this._isFrontFaceDirty = false;
  10763. };
  10764. _DepthCullingState.prototype.apply = function (gl) {
  10765. if (!this.isDirty) {
  10766. return;
  10767. }
  10768. // Cull
  10769. if (this._isCullDirty) {
  10770. if (this.cull) {
  10771. gl.enable(gl.CULL_FACE);
  10772. }
  10773. else {
  10774. gl.disable(gl.CULL_FACE);
  10775. }
  10776. this._isCullDirty = false;
  10777. }
  10778. // Cull face
  10779. if (this._isCullFaceDirty) {
  10780. gl.cullFace(this.cullFace);
  10781. this._isCullFaceDirty = false;
  10782. }
  10783. // Depth mask
  10784. if (this._isDepthMaskDirty) {
  10785. gl.depthMask(this.depthMask);
  10786. this._isDepthMaskDirty = false;
  10787. }
  10788. // Depth test
  10789. if (this._isDepthTestDirty) {
  10790. if (this.depthTest) {
  10791. gl.enable(gl.DEPTH_TEST);
  10792. }
  10793. else {
  10794. gl.disable(gl.DEPTH_TEST);
  10795. }
  10796. this._isDepthTestDirty = false;
  10797. }
  10798. // Depth func
  10799. if (this._isDepthFuncDirty) {
  10800. gl.depthFunc(this.depthFunc);
  10801. this._isDepthFuncDirty = false;
  10802. }
  10803. // zOffset
  10804. if (this._isZOffsetDirty) {
  10805. if (this.zOffset) {
  10806. gl.enable(gl.POLYGON_OFFSET_FILL);
  10807. gl.polygonOffset(this.zOffset, 0);
  10808. }
  10809. else {
  10810. gl.disable(gl.POLYGON_OFFSET_FILL);
  10811. }
  10812. this._isZOffsetDirty = false;
  10813. }
  10814. // Front face
  10815. if (this._isFrontFaceDirty) {
  10816. gl.frontFace(this.frontFace);
  10817. this._isFrontFaceDirty = false;
  10818. }
  10819. };
  10820. return _DepthCullingState;
  10821. }());
  10822. BABYLON._DepthCullingState = _DepthCullingState;
  10823. })(BABYLON || (BABYLON = {}));
  10824. //# sourceMappingURL=babylon.depthCullingState.js.map
  10825. var BABYLON;
  10826. (function (BABYLON) {
  10827. /**
  10828. * @hidden
  10829. **/
  10830. var _StencilState = /** @class */ (function () {
  10831. function _StencilState() {
  10832. this._isStencilTestDirty = false;
  10833. this._isStencilMaskDirty = false;
  10834. this._isStencilFuncDirty = false;
  10835. this._isStencilOpDirty = false;
  10836. this.reset();
  10837. }
  10838. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10839. get: function () {
  10840. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10841. },
  10842. enumerable: true,
  10843. configurable: true
  10844. });
  10845. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10846. get: function () {
  10847. return this._stencilFunc;
  10848. },
  10849. set: function (value) {
  10850. if (this._stencilFunc === value) {
  10851. return;
  10852. }
  10853. this._stencilFunc = value;
  10854. this._isStencilFuncDirty = true;
  10855. },
  10856. enumerable: true,
  10857. configurable: true
  10858. });
  10859. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10860. get: function () {
  10861. return this._stencilFuncRef;
  10862. },
  10863. set: function (value) {
  10864. if (this._stencilFuncRef === value) {
  10865. return;
  10866. }
  10867. this._stencilFuncRef = value;
  10868. this._isStencilFuncDirty = true;
  10869. },
  10870. enumerable: true,
  10871. configurable: true
  10872. });
  10873. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10874. get: function () {
  10875. return this._stencilFuncMask;
  10876. },
  10877. set: function (value) {
  10878. if (this._stencilFuncMask === value) {
  10879. return;
  10880. }
  10881. this._stencilFuncMask = value;
  10882. this._isStencilFuncDirty = true;
  10883. },
  10884. enumerable: true,
  10885. configurable: true
  10886. });
  10887. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10888. get: function () {
  10889. return this._stencilOpStencilFail;
  10890. },
  10891. set: function (value) {
  10892. if (this._stencilOpStencilFail === value) {
  10893. return;
  10894. }
  10895. this._stencilOpStencilFail = value;
  10896. this._isStencilOpDirty = true;
  10897. },
  10898. enumerable: true,
  10899. configurable: true
  10900. });
  10901. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10902. get: function () {
  10903. return this._stencilOpDepthFail;
  10904. },
  10905. set: function (value) {
  10906. if (this._stencilOpDepthFail === value) {
  10907. return;
  10908. }
  10909. this._stencilOpDepthFail = value;
  10910. this._isStencilOpDirty = true;
  10911. },
  10912. enumerable: true,
  10913. configurable: true
  10914. });
  10915. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10916. get: function () {
  10917. return this._stencilOpStencilDepthPass;
  10918. },
  10919. set: function (value) {
  10920. if (this._stencilOpStencilDepthPass === value) {
  10921. return;
  10922. }
  10923. this._stencilOpStencilDepthPass = value;
  10924. this._isStencilOpDirty = true;
  10925. },
  10926. enumerable: true,
  10927. configurable: true
  10928. });
  10929. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10930. get: function () {
  10931. return this._stencilMask;
  10932. },
  10933. set: function (value) {
  10934. if (this._stencilMask === value) {
  10935. return;
  10936. }
  10937. this._stencilMask = value;
  10938. this._isStencilMaskDirty = true;
  10939. },
  10940. enumerable: true,
  10941. configurable: true
  10942. });
  10943. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10944. get: function () {
  10945. return this._stencilTest;
  10946. },
  10947. set: function (value) {
  10948. if (this._stencilTest === value) {
  10949. return;
  10950. }
  10951. this._stencilTest = value;
  10952. this._isStencilTestDirty = true;
  10953. },
  10954. enumerable: true,
  10955. configurable: true
  10956. });
  10957. _StencilState.prototype.reset = function () {
  10958. this._stencilTest = false;
  10959. this._stencilMask = 0xFF;
  10960. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10961. this._stencilFuncRef = 1;
  10962. this._stencilFuncMask = 0xFF;
  10963. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10964. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10965. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10966. this._isStencilTestDirty = true;
  10967. this._isStencilMaskDirty = true;
  10968. this._isStencilFuncDirty = true;
  10969. this._isStencilOpDirty = true;
  10970. };
  10971. _StencilState.prototype.apply = function (gl) {
  10972. if (!this.isDirty) {
  10973. return;
  10974. }
  10975. // Stencil test
  10976. if (this._isStencilTestDirty) {
  10977. if (this.stencilTest) {
  10978. gl.enable(gl.STENCIL_TEST);
  10979. }
  10980. else {
  10981. gl.disable(gl.STENCIL_TEST);
  10982. }
  10983. this._isStencilTestDirty = false;
  10984. }
  10985. // Stencil mask
  10986. if (this._isStencilMaskDirty) {
  10987. gl.stencilMask(this.stencilMask);
  10988. this._isStencilMaskDirty = false;
  10989. }
  10990. // Stencil func
  10991. if (this._isStencilFuncDirty) {
  10992. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10993. this._isStencilFuncDirty = false;
  10994. }
  10995. // Stencil op
  10996. if (this._isStencilOpDirty) {
  10997. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10998. this._isStencilOpDirty = false;
  10999. }
  11000. };
  11001. return _StencilState;
  11002. }());
  11003. BABYLON._StencilState = _StencilState;
  11004. })(BABYLON || (BABYLON = {}));
  11005. //# sourceMappingURL=babylon.stencilState.js.map
  11006. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11007. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11008. s = arguments[i];
  11009. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11010. t[p] = s[p];
  11011. }
  11012. return t;
  11013. };
  11014. var BABYLON;
  11015. (function (BABYLON) {
  11016. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11017. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11018. };
  11019. var compileRawShader = function (gl, source, type) {
  11020. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11021. gl.shaderSource(shader, source);
  11022. gl.compileShader(shader);
  11023. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11024. var log = gl.getShaderInfoLog(shader);
  11025. if (log) {
  11026. throw new Error(log);
  11027. }
  11028. }
  11029. if (!shader) {
  11030. throw new Error("Something went wrong while compile the shader.");
  11031. }
  11032. return shader;
  11033. };
  11034. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11035. var magFilter = gl.NEAREST;
  11036. var minFilter = gl.NEAREST;
  11037. switch (samplingMode) {
  11038. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11039. magFilter = gl.LINEAR;
  11040. if (generateMipMaps) {
  11041. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11042. }
  11043. else {
  11044. minFilter = gl.LINEAR;
  11045. }
  11046. break;
  11047. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11048. magFilter = gl.LINEAR;
  11049. if (generateMipMaps) {
  11050. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11051. }
  11052. else {
  11053. minFilter = gl.LINEAR;
  11054. }
  11055. break;
  11056. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11057. magFilter = gl.NEAREST;
  11058. if (generateMipMaps) {
  11059. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11060. }
  11061. else {
  11062. minFilter = gl.NEAREST;
  11063. }
  11064. break;
  11065. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11066. magFilter = gl.NEAREST;
  11067. if (generateMipMaps) {
  11068. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11069. }
  11070. else {
  11071. minFilter = gl.NEAREST;
  11072. }
  11073. break;
  11074. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11075. magFilter = gl.NEAREST;
  11076. if (generateMipMaps) {
  11077. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11078. }
  11079. else {
  11080. minFilter = gl.LINEAR;
  11081. }
  11082. break;
  11083. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11084. magFilter = gl.NEAREST;
  11085. if (generateMipMaps) {
  11086. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11087. }
  11088. else {
  11089. minFilter = gl.LINEAR;
  11090. }
  11091. break;
  11092. case BABYLON.Texture.NEAREST_LINEAR:
  11093. magFilter = gl.NEAREST;
  11094. minFilter = gl.LINEAR;
  11095. break;
  11096. case BABYLON.Texture.NEAREST_NEAREST:
  11097. magFilter = gl.NEAREST;
  11098. minFilter = gl.NEAREST;
  11099. break;
  11100. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11101. magFilter = gl.LINEAR;
  11102. if (generateMipMaps) {
  11103. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11104. }
  11105. else {
  11106. minFilter = gl.NEAREST;
  11107. }
  11108. break;
  11109. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11110. magFilter = gl.LINEAR;
  11111. if (generateMipMaps) {
  11112. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11113. }
  11114. else {
  11115. minFilter = gl.NEAREST;
  11116. }
  11117. break;
  11118. case BABYLON.Texture.LINEAR_LINEAR:
  11119. magFilter = gl.LINEAR;
  11120. minFilter = gl.LINEAR;
  11121. break;
  11122. case BABYLON.Texture.LINEAR_NEAREST:
  11123. magFilter = gl.LINEAR;
  11124. minFilter = gl.NEAREST;
  11125. break;
  11126. }
  11127. return {
  11128. min: minFilter,
  11129. mag: magFilter
  11130. };
  11131. };
  11132. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11133. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11134. var img;
  11135. var onload = function () {
  11136. loadedImages[index] = img;
  11137. loadedImages._internalCount++;
  11138. if (scene) {
  11139. scene._removePendingData(img);
  11140. }
  11141. if (loadedImages._internalCount === 6) {
  11142. onfinish(loadedImages);
  11143. }
  11144. };
  11145. var onerror = function (message, exception) {
  11146. if (scene) {
  11147. scene._removePendingData(img);
  11148. }
  11149. if (onErrorCallBack) {
  11150. onErrorCallBack(message, exception);
  11151. }
  11152. };
  11153. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11154. if (scene) {
  11155. scene._addPendingData(img);
  11156. }
  11157. };
  11158. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11159. if (onError === void 0) { onError = null; }
  11160. var loadedImages = [];
  11161. loadedImages._internalCount = 0;
  11162. for (var index = 0; index < 6; index++) {
  11163. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11164. }
  11165. };
  11166. var BufferPointer = /** @class */ (function () {
  11167. function BufferPointer() {
  11168. }
  11169. return BufferPointer;
  11170. }());
  11171. /**
  11172. * Interface for attribute information associated with buffer instanciation
  11173. */
  11174. var InstancingAttributeInfo = /** @class */ (function () {
  11175. function InstancingAttributeInfo() {
  11176. }
  11177. return InstancingAttributeInfo;
  11178. }());
  11179. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11180. /**
  11181. * Define options used to create a render target texture
  11182. */
  11183. var RenderTargetCreationOptions = /** @class */ (function () {
  11184. function RenderTargetCreationOptions() {
  11185. }
  11186. return RenderTargetCreationOptions;
  11187. }());
  11188. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11189. /**
  11190. * Define options used to create a depth texture
  11191. */
  11192. var DepthTextureCreationOptions = /** @class */ (function () {
  11193. function DepthTextureCreationOptions() {
  11194. }
  11195. return DepthTextureCreationOptions;
  11196. }());
  11197. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11198. /**
  11199. * Class used to describe the capabilities of the engine relatively to the current browser
  11200. */
  11201. var EngineCapabilities = /** @class */ (function () {
  11202. function EngineCapabilities() {
  11203. }
  11204. return EngineCapabilities;
  11205. }());
  11206. BABYLON.EngineCapabilities = EngineCapabilities;
  11207. /**
  11208. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11209. */
  11210. var Engine = /** @class */ (function () {
  11211. /**
  11212. * Creates a new engine
  11213. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11214. * @param antialias defines enable antialiasing (default: false)
  11215. * @param options defines further options to be sent to the getContext() function
  11216. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11217. */
  11218. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11219. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11220. var _this = this;
  11221. // Public members
  11222. /**
  11223. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11224. */
  11225. this.forcePOTTextures = false;
  11226. /**
  11227. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11228. */
  11229. this.isFullscreen = false;
  11230. /**
  11231. * Gets a boolean indicating if the pointer is currently locked
  11232. */
  11233. this.isPointerLock = false;
  11234. /**
  11235. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11236. */
  11237. this.cullBackFaces = true;
  11238. /**
  11239. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11240. */
  11241. this.renderEvenInBackground = true;
  11242. /**
  11243. * Gets or sets a boolean indicating that cache can be kept between frames
  11244. */
  11245. this.preventCacheWipeBetweenFrames = false;
  11246. /**
  11247. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11248. **/
  11249. this.enableOfflineSupport = false;
  11250. /**
  11251. * 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)
  11252. **/
  11253. this.disableManifestCheck = false;
  11254. /**
  11255. * Gets the list of created scenes
  11256. */
  11257. this.scenes = new Array();
  11258. /**
  11259. * Gets the list of created postprocesses
  11260. */
  11261. this.postProcesses = new Array();
  11262. // Observables
  11263. /**
  11264. * Observable event triggered each time the rendering canvas is resized
  11265. */
  11266. this.onResizeObservable = new BABYLON.Observable();
  11267. /**
  11268. * Observable event triggered each time the canvas loses focus
  11269. */
  11270. this.onCanvasBlurObservable = new BABYLON.Observable();
  11271. /**
  11272. * Observable event triggered each time the canvas gains focus
  11273. */
  11274. this.onCanvasFocusObservable = new BABYLON.Observable();
  11275. /**
  11276. * Observable event triggered each time the canvas receives pointerout event
  11277. */
  11278. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11279. /**
  11280. * Observable event triggered before each texture is initialized
  11281. */
  11282. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11283. //WebVR
  11284. this._vrDisplay = undefined;
  11285. this._vrSupported = false;
  11286. this._vrExclusivePointerMode = false;
  11287. // Uniform buffers list
  11288. /**
  11289. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11290. */
  11291. this.disableUniformBuffers = false;
  11292. /** @hidden */
  11293. this._uniformBuffers = new Array();
  11294. // Observables
  11295. /**
  11296. * Observable raised when the engine begins a new frame
  11297. */
  11298. this.onBeginFrameObservable = new BABYLON.Observable();
  11299. /**
  11300. * Observable raised when the engine ends the current frame
  11301. */
  11302. this.onEndFrameObservable = new BABYLON.Observable();
  11303. /**
  11304. * Observable raised when the engine is about to compile a shader
  11305. */
  11306. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11307. /**
  11308. * Observable raised when the engine has jsut compiled a shader
  11309. */
  11310. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11311. this._windowIsBackground = false;
  11312. this._webGLVersion = 1.0;
  11313. /** @hidden */
  11314. this._badOS = false;
  11315. /** @hidden */
  11316. this._badDesktopOS = false;
  11317. /**
  11318. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11319. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11320. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11321. */
  11322. this.disableTextureBindingOptimization = false;
  11323. /**
  11324. * Observable signaled when VR display mode changes
  11325. */
  11326. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11327. /**
  11328. * Observable signaled when VR request present is complete
  11329. */
  11330. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11331. /**
  11332. * Observable signaled when VR request present starts
  11333. */
  11334. this.onVRRequestPresentStart = new BABYLON.Observable();
  11335. this._colorWrite = true;
  11336. /** @hidden */
  11337. this._drawCalls = new BABYLON.PerfCounter();
  11338. /** @hidden */
  11339. this._textureCollisions = new BABYLON.PerfCounter();
  11340. this._renderingQueueLaunched = false;
  11341. this._activeRenderLoops = new Array();
  11342. // Deterministic lockstepMaxSteps
  11343. this._deterministicLockstep = false;
  11344. this._lockstepMaxSteps = 4;
  11345. // Lost context
  11346. /**
  11347. * Observable signaled when a context lost event is raised
  11348. */
  11349. this.onContextLostObservable = new BABYLON.Observable();
  11350. /**
  11351. * Observable signaled when a context restored event is raised
  11352. */
  11353. this.onContextRestoredObservable = new BABYLON.Observable();
  11354. this._contextWasLost = false;
  11355. this._doNotHandleContextLost = false;
  11356. // FPS
  11357. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11358. this._fps = 60;
  11359. this._deltaTime = 0;
  11360. /**
  11361. * Turn this value on if you want to pause FPS computation when in background
  11362. */
  11363. this.disablePerformanceMonitorInBackground = false;
  11364. // States
  11365. /** @hidden */
  11366. this._depthCullingState = new BABYLON._DepthCullingState();
  11367. /** @hidden */
  11368. this._stencilState = new BABYLON._StencilState();
  11369. /** @hidden */
  11370. this._alphaState = new BABYLON._AlphaState();
  11371. /** @hidden */
  11372. this._alphaMode = Engine.ALPHA_DISABLE;
  11373. // Cache
  11374. this._internalTexturesCache = new Array();
  11375. /** @hidden */
  11376. this._activeChannel = 0;
  11377. this._currentTextureChannel = -1;
  11378. /** @hidden */
  11379. this._boundTexturesCache = {};
  11380. this._compiledEffects = {};
  11381. this._vertexAttribArraysEnabled = [];
  11382. this._uintIndicesCurrentlySet = false;
  11383. this._currentBoundBuffer = new Array();
  11384. this._currentBufferPointers = new Array();
  11385. this._currentInstanceLocations = new Array();
  11386. this._currentInstanceBuffers = new Array();
  11387. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11388. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11389. this._vaoRecordInProgress = false;
  11390. this._mustWipeVertexAttributes = false;
  11391. this._nextFreeTextureSlots = new Array();
  11392. this._maxSimultaneousTextures = 0;
  11393. this._activeRequests = new Array();
  11394. // Hardware supported Compressed Textures
  11395. this._texturesSupported = new Array();
  11396. /**
  11397. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11398. */
  11399. this.premultipliedAlpha = true;
  11400. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11401. this._onVRFullScreenTriggered = function () {
  11402. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11403. //get the old size before we change
  11404. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11405. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11406. //get the width and height, change the render size
  11407. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11408. _this.setHardwareScalingLevel(1);
  11409. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11410. }
  11411. else {
  11412. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11413. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11414. }
  11415. };
  11416. this._unpackFlipYCached = null;
  11417. this._boundUniforms = {};
  11418. // Register promises
  11419. BABYLON.PromisePolyfill.Apply();
  11420. var canvas = null;
  11421. Engine.Instances.push(this);
  11422. if (!canvasOrContext) {
  11423. return;
  11424. }
  11425. options = options || {};
  11426. if (canvasOrContext.getContext) {
  11427. canvas = canvasOrContext;
  11428. this._renderingCanvas = canvas;
  11429. if (antialias != null) {
  11430. options.antialias = antialias;
  11431. }
  11432. if (options.deterministicLockstep === undefined) {
  11433. options.deterministicLockstep = false;
  11434. }
  11435. if (options.lockstepMaxSteps === undefined) {
  11436. options.lockstepMaxSteps = 4;
  11437. }
  11438. if (options.preserveDrawingBuffer === undefined) {
  11439. options.preserveDrawingBuffer = false;
  11440. }
  11441. if (options.audioEngine === undefined) {
  11442. options.audioEngine = true;
  11443. }
  11444. if (options.stencil === undefined) {
  11445. options.stencil = true;
  11446. }
  11447. if (options.premultipliedAlpha === false) {
  11448. this.premultipliedAlpha = false;
  11449. }
  11450. this._deterministicLockstep = options.deterministicLockstep;
  11451. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11452. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11453. // Exceptions
  11454. if (navigator && navigator.userAgent) {
  11455. var ua = navigator.userAgent;
  11456. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11457. var exception = _a[_i];
  11458. var key = exception.key;
  11459. var targets = exception.targets;
  11460. if (ua.indexOf(key) > -1) {
  11461. if (exception.capture && exception.captureConstraint) {
  11462. var capture = exception.capture;
  11463. var constraint = exception.captureConstraint;
  11464. var regex = new RegExp(capture);
  11465. var matches = regex.exec(ua);
  11466. if (matches && matches.length > 0) {
  11467. var capturedValue = parseInt(matches[matches.length - 1]);
  11468. if (capturedValue >= constraint) {
  11469. continue;
  11470. }
  11471. }
  11472. }
  11473. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11474. var target = targets_1[_b];
  11475. switch (target) {
  11476. case "uniformBuffer":
  11477. this.disableUniformBuffers = true;
  11478. break;
  11479. case "textureBindingOptimization":
  11480. this.disableTextureBindingOptimization = true;
  11481. break;
  11482. }
  11483. }
  11484. }
  11485. }
  11486. }
  11487. // GL
  11488. if (!options.disableWebGL2Support) {
  11489. try {
  11490. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11491. if (this._gl) {
  11492. this._webGLVersion = 2.0;
  11493. }
  11494. }
  11495. catch (e) {
  11496. // Do nothing
  11497. }
  11498. }
  11499. if (!this._gl) {
  11500. if (!canvas) {
  11501. throw new Error("The provided canvas is null or undefined.");
  11502. }
  11503. try {
  11504. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11505. }
  11506. catch (e) {
  11507. throw new Error("WebGL not supported");
  11508. }
  11509. }
  11510. if (!this._gl) {
  11511. throw new Error("WebGL not supported");
  11512. }
  11513. this._onCanvasFocus = function () {
  11514. _this.onCanvasFocusObservable.notifyObservers(_this);
  11515. };
  11516. this._onCanvasBlur = function () {
  11517. _this.onCanvasBlurObservable.notifyObservers(_this);
  11518. };
  11519. canvas.addEventListener("focus", this._onCanvasFocus);
  11520. canvas.addEventListener("blur", this._onCanvasBlur);
  11521. this._onBlur = function () {
  11522. if (_this.disablePerformanceMonitorInBackground) {
  11523. _this._performanceMonitor.disable();
  11524. }
  11525. _this._windowIsBackground = true;
  11526. };
  11527. this._onFocus = function () {
  11528. if (_this.disablePerformanceMonitorInBackground) {
  11529. _this._performanceMonitor.enable();
  11530. }
  11531. _this._windowIsBackground = false;
  11532. };
  11533. this._onCanvasPointerOut = function (ev) {
  11534. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11535. };
  11536. window.addEventListener("blur", this._onBlur);
  11537. window.addEventListener("focus", this._onFocus);
  11538. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11539. // Context lost
  11540. if (!this._doNotHandleContextLost) {
  11541. this._onContextLost = function (evt) {
  11542. evt.preventDefault();
  11543. _this._contextWasLost = true;
  11544. BABYLON.Tools.Warn("WebGL context lost.");
  11545. _this.onContextLostObservable.notifyObservers(_this);
  11546. };
  11547. this._onContextRestored = function (evt) {
  11548. // Adding a timeout to avoid race condition at browser level
  11549. setTimeout(function () {
  11550. // Rebuild gl context
  11551. _this._initGLContext();
  11552. // Rebuild effects
  11553. _this._rebuildEffects();
  11554. // Rebuild textures
  11555. _this._rebuildInternalTextures();
  11556. // Rebuild buffers
  11557. _this._rebuildBuffers();
  11558. // Cache
  11559. _this.wipeCaches(true);
  11560. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11561. _this.onContextRestoredObservable.notifyObservers(_this);
  11562. _this._contextWasLost = false;
  11563. }, 0);
  11564. };
  11565. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11566. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11567. }
  11568. }
  11569. else {
  11570. this._gl = canvasOrContext;
  11571. this._renderingCanvas = this._gl.canvas;
  11572. if (this._gl.renderbufferStorageMultisample) {
  11573. this._webGLVersion = 2.0;
  11574. }
  11575. options.stencil = this._gl.getContextAttributes().stencil;
  11576. }
  11577. // Viewport
  11578. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11579. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11580. this.resize();
  11581. this._isStencilEnable = options.stencil ? true : false;
  11582. this._initGLContext();
  11583. if (canvas) {
  11584. // Fullscreen
  11585. this._onFullscreenChange = function () {
  11586. if (document.fullscreen !== undefined) {
  11587. _this.isFullscreen = document.fullscreen;
  11588. }
  11589. else if (document.mozFullScreen !== undefined) {
  11590. _this.isFullscreen = document.mozFullScreen;
  11591. }
  11592. else if (document.webkitIsFullScreen !== undefined) {
  11593. _this.isFullscreen = document.webkitIsFullScreen;
  11594. }
  11595. else if (document.msIsFullScreen !== undefined) {
  11596. _this.isFullscreen = document.msIsFullScreen;
  11597. }
  11598. // Pointer lock
  11599. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11600. canvas.requestPointerLock = canvas.requestPointerLock ||
  11601. canvas.msRequestPointerLock ||
  11602. canvas.mozRequestPointerLock ||
  11603. canvas.webkitRequestPointerLock;
  11604. if (canvas.requestPointerLock) {
  11605. canvas.requestPointerLock();
  11606. }
  11607. }
  11608. };
  11609. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11610. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11611. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11612. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11613. // Pointer lock
  11614. this._onPointerLockChange = function () {
  11615. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11616. document.webkitPointerLockElement === canvas ||
  11617. document.msPointerLockElement === canvas ||
  11618. document.pointerLockElement === canvas);
  11619. };
  11620. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11621. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11622. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11623. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11624. this._onVRDisplayPointerRestricted = function () {
  11625. if (canvas) {
  11626. canvas.requestPointerLock();
  11627. }
  11628. };
  11629. this._onVRDisplayPointerUnrestricted = function () {
  11630. document.exitPointerLock();
  11631. };
  11632. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11633. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11634. }
  11635. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11636. Engine.audioEngine = new BABYLON.AudioEngine();
  11637. }
  11638. // Prepare buffer pointers
  11639. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11640. this._currentBufferPointers[i] = new BufferPointer();
  11641. }
  11642. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11643. // Load WebVR Devices
  11644. if (options.autoEnableWebVR) {
  11645. this.initWebVR();
  11646. }
  11647. // Detect if we are running on a faulty buggy OS.
  11648. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11649. // Detect if we are running on a faulty buggy desktop OS.
  11650. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11651. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11652. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11653. }
  11654. Object.defineProperty(Engine, "LastCreatedEngine", {
  11655. /**
  11656. * Gets the latest created engine
  11657. */
  11658. get: function () {
  11659. if (Engine.Instances.length === 0) {
  11660. return null;
  11661. }
  11662. return Engine.Instances[Engine.Instances.length - 1];
  11663. },
  11664. enumerable: true,
  11665. configurable: true
  11666. });
  11667. Object.defineProperty(Engine, "LastCreatedScene", {
  11668. /**
  11669. * Gets the latest created scene
  11670. */
  11671. get: function () {
  11672. var lastCreatedEngine = Engine.LastCreatedEngine;
  11673. if (!lastCreatedEngine) {
  11674. return null;
  11675. }
  11676. if (lastCreatedEngine.scenes.length === 0) {
  11677. return null;
  11678. }
  11679. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11680. },
  11681. enumerable: true,
  11682. configurable: true
  11683. });
  11684. /**
  11685. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11686. * @param flag defines which part of the materials must be marked as dirty
  11687. * @param predicate defines a predicate used to filter which materials should be affected
  11688. */
  11689. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11690. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11691. var engine = Engine.Instances[engineIndex];
  11692. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11693. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11694. }
  11695. }
  11696. };
  11697. Object.defineProperty(Engine, "NEVER", {
  11698. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11699. get: function () {
  11700. return Engine._NEVER;
  11701. },
  11702. enumerable: true,
  11703. configurable: true
  11704. });
  11705. Object.defineProperty(Engine, "ALWAYS", {
  11706. /** 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 */
  11707. get: function () {
  11708. return Engine._ALWAYS;
  11709. },
  11710. enumerable: true,
  11711. configurable: true
  11712. });
  11713. Object.defineProperty(Engine, "LESS", {
  11714. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11715. get: function () {
  11716. return Engine._LESS;
  11717. },
  11718. enumerable: true,
  11719. configurable: true
  11720. });
  11721. Object.defineProperty(Engine, "EQUAL", {
  11722. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11723. get: function () {
  11724. return Engine._EQUAL;
  11725. },
  11726. enumerable: true,
  11727. configurable: true
  11728. });
  11729. Object.defineProperty(Engine, "LEQUAL", {
  11730. /** 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 */
  11731. get: function () {
  11732. return Engine._LEQUAL;
  11733. },
  11734. enumerable: true,
  11735. configurable: true
  11736. });
  11737. Object.defineProperty(Engine, "GREATER", {
  11738. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11739. get: function () {
  11740. return Engine._GREATER;
  11741. },
  11742. enumerable: true,
  11743. configurable: true
  11744. });
  11745. Object.defineProperty(Engine, "GEQUAL", {
  11746. /** 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 */
  11747. get: function () {
  11748. return Engine._GEQUAL;
  11749. },
  11750. enumerable: true,
  11751. configurable: true
  11752. });
  11753. Object.defineProperty(Engine, "NOTEQUAL", {
  11754. /** 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 */
  11755. get: function () {
  11756. return Engine._NOTEQUAL;
  11757. },
  11758. enumerable: true,
  11759. configurable: true
  11760. });
  11761. Object.defineProperty(Engine, "KEEP", {
  11762. /** Passed to stencilOperation to specify that stencil value must be kept */
  11763. get: function () {
  11764. return Engine._KEEP;
  11765. },
  11766. enumerable: true,
  11767. configurable: true
  11768. });
  11769. Object.defineProperty(Engine, "REPLACE", {
  11770. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11771. get: function () {
  11772. return Engine._REPLACE;
  11773. },
  11774. enumerable: true,
  11775. configurable: true
  11776. });
  11777. Object.defineProperty(Engine, "INCR", {
  11778. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11779. get: function () {
  11780. return Engine._INCR;
  11781. },
  11782. enumerable: true,
  11783. configurable: true
  11784. });
  11785. Object.defineProperty(Engine, "DECR", {
  11786. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11787. get: function () {
  11788. return Engine._DECR;
  11789. },
  11790. enumerable: true,
  11791. configurable: true
  11792. });
  11793. Object.defineProperty(Engine, "INVERT", {
  11794. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11795. get: function () {
  11796. return Engine._INVERT;
  11797. },
  11798. enumerable: true,
  11799. configurable: true
  11800. });
  11801. Object.defineProperty(Engine, "INCR_WRAP", {
  11802. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11803. get: function () {
  11804. return Engine._INCR_WRAP;
  11805. },
  11806. enumerable: true,
  11807. configurable: true
  11808. });
  11809. Object.defineProperty(Engine, "DECR_WRAP", {
  11810. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11811. get: function () {
  11812. return Engine._DECR_WRAP;
  11813. },
  11814. enumerable: true,
  11815. configurable: true
  11816. });
  11817. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11818. // Alpha
  11819. /** Defines that alpha blending is disabled */
  11820. get: function () {
  11821. return Engine._ALPHA_DISABLE;
  11822. },
  11823. enumerable: true,
  11824. configurable: true
  11825. });
  11826. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11827. /** Defines that alpha blending to SRC + DEST */
  11828. get: function () {
  11829. return Engine._ALPHA_ONEONE;
  11830. },
  11831. enumerable: true,
  11832. configurable: true
  11833. });
  11834. Object.defineProperty(Engine, "ALPHA_ADD", {
  11835. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11836. get: function () {
  11837. return Engine._ALPHA_ADD;
  11838. },
  11839. enumerable: true,
  11840. configurable: true
  11841. });
  11842. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11843. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11844. get: function () {
  11845. return Engine._ALPHA_COMBINE;
  11846. },
  11847. enumerable: true,
  11848. configurable: true
  11849. });
  11850. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11851. /** Defines that alpha blending to DEST - SRC * DEST */
  11852. get: function () {
  11853. return Engine._ALPHA_SUBTRACT;
  11854. },
  11855. enumerable: true,
  11856. configurable: true
  11857. });
  11858. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11859. /** Defines that alpha blending to SRC * DEST */
  11860. get: function () {
  11861. return Engine._ALPHA_MULTIPLY;
  11862. },
  11863. enumerable: true,
  11864. configurable: true
  11865. });
  11866. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11867. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11868. get: function () {
  11869. return Engine._ALPHA_MAXIMIZED;
  11870. },
  11871. enumerable: true,
  11872. configurable: true
  11873. });
  11874. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11875. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11876. get: function () {
  11877. return Engine._ALPHA_PREMULTIPLIED;
  11878. },
  11879. enumerable: true,
  11880. configurable: true
  11881. });
  11882. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11883. /**
  11884. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11885. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11886. */
  11887. get: function () {
  11888. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11889. },
  11890. enumerable: true,
  11891. configurable: true
  11892. });
  11893. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11894. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11895. get: function () {
  11896. return Engine._ALPHA_INTERPOLATE;
  11897. },
  11898. enumerable: true,
  11899. configurable: true
  11900. });
  11901. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11902. /**
  11903. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11904. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11905. */
  11906. get: function () {
  11907. return Engine._ALPHA_SCREENMODE;
  11908. },
  11909. enumerable: true,
  11910. configurable: true
  11911. });
  11912. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11913. // Delays
  11914. /** Defines that the ressource is not delayed*/
  11915. get: function () {
  11916. return Engine._DELAYLOADSTATE_NONE;
  11917. },
  11918. enumerable: true,
  11919. configurable: true
  11920. });
  11921. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11922. /** Defines that the ressource was successfully delay loaded */
  11923. get: function () {
  11924. return Engine._DELAYLOADSTATE_LOADED;
  11925. },
  11926. enumerable: true,
  11927. configurable: true
  11928. });
  11929. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11930. /** Defines that the ressource is currently delay loading */
  11931. get: function () {
  11932. return Engine._DELAYLOADSTATE_LOADING;
  11933. },
  11934. enumerable: true,
  11935. configurable: true
  11936. });
  11937. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11938. /** Defines that the ressource is delayed and has not started loading */
  11939. get: function () {
  11940. return Engine._DELAYLOADSTATE_NOTLOADED;
  11941. },
  11942. enumerable: true,
  11943. configurable: true
  11944. });
  11945. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11946. /** ALPHA */
  11947. get: function () {
  11948. return Engine._TEXTUREFORMAT_ALPHA;
  11949. },
  11950. enumerable: true,
  11951. configurable: true
  11952. });
  11953. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11954. /** LUMINANCE */
  11955. get: function () {
  11956. return Engine._TEXTUREFORMAT_LUMINANCE;
  11957. },
  11958. enumerable: true,
  11959. configurable: true
  11960. });
  11961. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  11962. /**
  11963. * R
  11964. */
  11965. get: function () {
  11966. return Engine._TEXTUREFORMAT_R;
  11967. },
  11968. enumerable: true,
  11969. configurable: true
  11970. });
  11971. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  11972. /**
  11973. * RG
  11974. */
  11975. get: function () {
  11976. return Engine._TEXTUREFORMAT_RG;
  11977. },
  11978. enumerable: true,
  11979. configurable: true
  11980. });
  11981. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11982. /** LUMINANCE_ALPHA */
  11983. get: function () {
  11984. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11985. },
  11986. enumerable: true,
  11987. configurable: true
  11988. });
  11989. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11990. /** RGB */
  11991. get: function () {
  11992. return Engine._TEXTUREFORMAT_RGB;
  11993. },
  11994. enumerable: true,
  11995. configurable: true
  11996. });
  11997. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11998. /** RGBA */
  11999. get: function () {
  12000. return Engine._TEXTUREFORMAT_RGBA;
  12001. },
  12002. enumerable: true,
  12003. configurable: true
  12004. });
  12005. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12006. /** UNSIGNED_INT */
  12007. get: function () {
  12008. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12009. },
  12010. enumerable: true,
  12011. configurable: true
  12012. });
  12013. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12014. /** FLOAT */
  12015. get: function () {
  12016. return Engine._TEXTURETYPE_FLOAT;
  12017. },
  12018. enumerable: true,
  12019. configurable: true
  12020. });
  12021. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12022. /** HALF_FLOAT */
  12023. get: function () {
  12024. return Engine._TEXTURETYPE_HALF_FLOAT;
  12025. },
  12026. enumerable: true,
  12027. configurable: true
  12028. });
  12029. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12030. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12031. get: function () {
  12032. return Engine._SCALEMODE_FLOOR;
  12033. },
  12034. enumerable: true,
  12035. configurable: true
  12036. });
  12037. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12038. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12039. get: function () {
  12040. return Engine._SCALEMODE_NEAREST;
  12041. },
  12042. enumerable: true,
  12043. configurable: true
  12044. });
  12045. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12046. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12047. get: function () {
  12048. return Engine._SCALEMODE_CEILING;
  12049. },
  12050. enumerable: true,
  12051. configurable: true
  12052. });
  12053. Object.defineProperty(Engine, "Version", {
  12054. /**
  12055. * Returns the current version of the framework
  12056. */
  12057. get: function () {
  12058. return "3.3.0-alpha.8";
  12059. },
  12060. enumerable: true,
  12061. configurable: true
  12062. });
  12063. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12064. /**
  12065. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12066. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12067. */
  12068. get: function () {
  12069. return this._vrExclusivePointerMode;
  12070. },
  12071. enumerable: true,
  12072. configurable: true
  12073. });
  12074. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12075. /**
  12076. * Gets a boolean indicating that the engine supports uniform buffers
  12077. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12078. */
  12079. get: function () {
  12080. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12081. },
  12082. enumerable: true,
  12083. configurable: true
  12084. });
  12085. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12086. /**
  12087. * Gets a boolean indicating that only power of 2 textures are supported
  12088. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12089. */
  12090. get: function () {
  12091. return this._webGLVersion < 2 || this.forcePOTTextures;
  12092. },
  12093. enumerable: true,
  12094. configurable: true
  12095. });
  12096. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12097. /**
  12098. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12099. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12100. */
  12101. get: function () {
  12102. return this._doNotHandleContextLost;
  12103. },
  12104. set: function (value) {
  12105. this._doNotHandleContextLost = value;
  12106. },
  12107. enumerable: true,
  12108. configurable: true
  12109. });
  12110. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12111. /**
  12112. * Gets the performance monitor attached to this engine
  12113. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12114. */
  12115. get: function () {
  12116. return this._performanceMonitor;
  12117. },
  12118. enumerable: true,
  12119. configurable: true
  12120. });
  12121. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12122. /**
  12123. * Gets the list of texture formats supported
  12124. */
  12125. get: function () {
  12126. return this._texturesSupported;
  12127. },
  12128. enumerable: true,
  12129. configurable: true
  12130. });
  12131. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12132. /**
  12133. * Gets the list of texture formats in use
  12134. */
  12135. get: function () {
  12136. return this._textureFormatInUse;
  12137. },
  12138. enumerable: true,
  12139. configurable: true
  12140. });
  12141. Object.defineProperty(Engine.prototype, "currentViewport", {
  12142. /**
  12143. * Gets the current viewport
  12144. */
  12145. get: function () {
  12146. return this._cachedViewport;
  12147. },
  12148. enumerable: true,
  12149. configurable: true
  12150. });
  12151. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12152. /**
  12153. * Gets the default empty texture
  12154. */
  12155. get: function () {
  12156. if (!this._emptyTexture) {
  12157. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12158. }
  12159. return this._emptyTexture;
  12160. },
  12161. enumerable: true,
  12162. configurable: true
  12163. });
  12164. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12165. /**
  12166. * Gets the default empty 3D texture
  12167. */
  12168. get: function () {
  12169. if (!this._emptyTexture3D) {
  12170. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12171. }
  12172. return this._emptyTexture3D;
  12173. },
  12174. enumerable: true,
  12175. configurable: true
  12176. });
  12177. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12178. /**
  12179. * Gets the default empty cube texture
  12180. */
  12181. get: function () {
  12182. if (!this._emptyCubeTexture) {
  12183. var faceData = new Uint8Array(4);
  12184. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12185. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12186. }
  12187. return this._emptyCubeTexture;
  12188. },
  12189. enumerable: true,
  12190. configurable: true
  12191. });
  12192. Engine.prototype._rebuildInternalTextures = function () {
  12193. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12194. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12195. var internalTexture = currentState_1[_i];
  12196. internalTexture._rebuild();
  12197. }
  12198. };
  12199. Engine.prototype._rebuildEffects = function () {
  12200. for (var key in this._compiledEffects) {
  12201. var effect = this._compiledEffects[key];
  12202. effect._prepareEffect();
  12203. }
  12204. BABYLON.Effect.ResetCache();
  12205. };
  12206. Engine.prototype._rebuildBuffers = function () {
  12207. // Index / Vertex
  12208. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12209. var scene = _a[_i];
  12210. scene.resetCachedMaterial();
  12211. scene._rebuildGeometries();
  12212. scene._rebuildTextures();
  12213. }
  12214. // Uniforms
  12215. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12216. var uniformBuffer = _c[_b];
  12217. uniformBuffer._rebuild();
  12218. }
  12219. };
  12220. Engine.prototype._initGLContext = function () {
  12221. // Caps
  12222. this._caps = new EngineCapabilities();
  12223. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12224. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12225. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12226. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12227. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12228. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12229. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12230. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12231. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12232. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12233. // Infos
  12234. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12235. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12236. if (rendererInfo != null) {
  12237. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12238. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12239. }
  12240. if (!this._glVendor) {
  12241. this._glVendor = "Unknown vendor";
  12242. }
  12243. if (!this._glRenderer) {
  12244. this._glRenderer = "Unknown renderer";
  12245. }
  12246. // Constants
  12247. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12248. if (this._gl.RGBA16F !== 0x881A) {
  12249. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12250. }
  12251. if (this._gl.RGBA32F !== 0x8814) {
  12252. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12253. }
  12254. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12255. this._gl.DEPTH24_STENCIL8 = 35056;
  12256. }
  12257. // Extensions
  12258. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12259. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12260. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12261. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12262. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12263. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12264. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12265. 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');
  12266. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12267. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12268. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12269. this._caps.highPrecisionShaderSupported = true;
  12270. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12271. if (this._caps.timerQuery) {
  12272. if (this._webGLVersion === 1) {
  12273. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12274. }
  12275. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12276. }
  12277. // Checks if some of the format renders first to allow the use of webgl inspector.
  12278. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12279. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12280. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12281. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12282. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12283. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12284. if (this._webGLVersion > 1) {
  12285. this._gl.HALF_FLOAT_OES = 0x140B;
  12286. }
  12287. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12288. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12289. // Draw buffers
  12290. if (this._webGLVersion > 1) {
  12291. this._caps.drawBuffersExtension = true;
  12292. }
  12293. else {
  12294. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12295. if (drawBuffersExtension !== null) {
  12296. this._caps.drawBuffersExtension = true;
  12297. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12298. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12299. for (var i = 0; i < 16; i++) {
  12300. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12301. }
  12302. }
  12303. else {
  12304. this._caps.drawBuffersExtension = false;
  12305. }
  12306. }
  12307. // Depth Texture
  12308. if (this._webGLVersion > 1) {
  12309. this._caps.depthTextureExtension = true;
  12310. }
  12311. else {
  12312. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12313. if (depthTextureExtension != null) {
  12314. this._caps.depthTextureExtension = true;
  12315. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12316. }
  12317. }
  12318. // Vertex array object
  12319. if (this._webGLVersion > 1) {
  12320. this._caps.vertexArrayObject = true;
  12321. }
  12322. else {
  12323. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12324. if (vertexArrayObjectExtension != null) {
  12325. this._caps.vertexArrayObject = true;
  12326. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12327. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12328. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12329. }
  12330. else {
  12331. this._caps.vertexArrayObject = false;
  12332. }
  12333. }
  12334. // Instances count
  12335. if (this._webGLVersion > 1) {
  12336. this._caps.instancedArrays = true;
  12337. }
  12338. else {
  12339. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12340. if (instanceExtension != null) {
  12341. this._caps.instancedArrays = true;
  12342. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12343. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12344. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12345. }
  12346. else {
  12347. this._caps.instancedArrays = false;
  12348. }
  12349. }
  12350. // Intelligently add supported compressed formats in order to check for.
  12351. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12352. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12353. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12354. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12355. if (this._caps.astc)
  12356. this.texturesSupported.push('-astc.ktx');
  12357. if (this._caps.s3tc)
  12358. this.texturesSupported.push('-dxt.ktx');
  12359. if (this._caps.pvrtc)
  12360. this.texturesSupported.push('-pvrtc.ktx');
  12361. if (this._caps.etc2)
  12362. this.texturesSupported.push('-etc2.ktx');
  12363. if (this._caps.etc1)
  12364. this.texturesSupported.push('-etc1.ktx');
  12365. if (this._gl.getShaderPrecisionFormat) {
  12366. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12367. if (highp) {
  12368. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12369. }
  12370. }
  12371. // Depth buffer
  12372. this.setDepthBuffer(true);
  12373. this.setDepthFunctionToLessOrEqual();
  12374. this.setDepthWrite(true);
  12375. // Texture maps
  12376. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12377. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12378. this._nextFreeTextureSlots.push(slot);
  12379. }
  12380. };
  12381. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12382. /**
  12383. * Gets version of the current webGL context
  12384. */
  12385. get: function () {
  12386. return this._webGLVersion;
  12387. },
  12388. enumerable: true,
  12389. configurable: true
  12390. });
  12391. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12392. /**
  12393. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12394. */
  12395. get: function () {
  12396. return this._isStencilEnable;
  12397. },
  12398. enumerable: true,
  12399. configurable: true
  12400. });
  12401. Engine.prototype._prepareWorkingCanvas = function () {
  12402. if (this._workingCanvas) {
  12403. return;
  12404. }
  12405. this._workingCanvas = document.createElement("canvas");
  12406. var context = this._workingCanvas.getContext("2d");
  12407. if (context) {
  12408. this._workingContext = context;
  12409. }
  12410. };
  12411. /**
  12412. * Reset the texture cache to empty state
  12413. */
  12414. Engine.prototype.resetTextureCache = function () {
  12415. for (var key in this._boundTexturesCache) {
  12416. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12417. continue;
  12418. }
  12419. var boundTexture = this._boundTexturesCache[key];
  12420. if (boundTexture) {
  12421. this._removeDesignatedSlot(boundTexture);
  12422. }
  12423. this._boundTexturesCache[key] = null;
  12424. }
  12425. if (!this.disableTextureBindingOptimization) {
  12426. this._nextFreeTextureSlots = [];
  12427. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12428. this._nextFreeTextureSlots.push(slot);
  12429. }
  12430. }
  12431. this._currentTextureChannel = -1;
  12432. };
  12433. /**
  12434. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12435. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12436. * @returns true if engine is in deterministic lock step mode
  12437. */
  12438. Engine.prototype.isDeterministicLockStep = function () {
  12439. return this._deterministicLockstep;
  12440. };
  12441. /**
  12442. * Gets the max steps when engine is running in deterministic lock step
  12443. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12444. * @returns the max steps
  12445. */
  12446. Engine.prototype.getLockstepMaxSteps = function () {
  12447. return this._lockstepMaxSteps;
  12448. };
  12449. /**
  12450. * Gets an object containing information about the current webGL context
  12451. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12452. */
  12453. Engine.prototype.getGlInfo = function () {
  12454. return {
  12455. vendor: this._glVendor,
  12456. renderer: this._glRenderer,
  12457. version: this._glVersion
  12458. };
  12459. };
  12460. /**
  12461. * Gets current aspect ratio
  12462. * @param camera defines the camera to use to get the aspect ratio
  12463. * @param useScreen defines if screen size must be used (or the current render target if any)
  12464. * @returns a number defining the aspect ratio
  12465. */
  12466. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12467. if (useScreen === void 0) { useScreen = false; }
  12468. var viewport = camera.viewport;
  12469. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12470. };
  12471. /**
  12472. * Gets current screen aspect ratio
  12473. * @returns a number defining the aspect ratio
  12474. */
  12475. Engine.prototype.getScreenAspectRatio = function () {
  12476. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12477. };
  12478. /**
  12479. * Gets the current render width
  12480. * @param useScreen defines if screen size must be used (or the current render target if any)
  12481. * @returns a number defining the current render width
  12482. */
  12483. Engine.prototype.getRenderWidth = function (useScreen) {
  12484. if (useScreen === void 0) { useScreen = false; }
  12485. if (!useScreen && this._currentRenderTarget) {
  12486. return this._currentRenderTarget.width;
  12487. }
  12488. return this._gl.drawingBufferWidth;
  12489. };
  12490. /**
  12491. * Gets the current render height
  12492. * @param useScreen defines if screen size must be used (or the current render target if any)
  12493. * @returns a number defining the current render height
  12494. */
  12495. Engine.prototype.getRenderHeight = function (useScreen) {
  12496. if (useScreen === void 0) { useScreen = false; }
  12497. if (!useScreen && this._currentRenderTarget) {
  12498. return this._currentRenderTarget.height;
  12499. }
  12500. return this._gl.drawingBufferHeight;
  12501. };
  12502. /**
  12503. * Gets the HTML canvas attached with the current webGL context
  12504. * @returns a HTML canvas
  12505. */
  12506. Engine.prototype.getRenderingCanvas = function () {
  12507. return this._renderingCanvas;
  12508. };
  12509. /**
  12510. * Gets the client rect of the HTML canvas attached with the current webGL context
  12511. * @returns a client rectanglee
  12512. */
  12513. Engine.prototype.getRenderingCanvasClientRect = function () {
  12514. if (!this._renderingCanvas) {
  12515. return null;
  12516. }
  12517. return this._renderingCanvas.getBoundingClientRect();
  12518. };
  12519. /**
  12520. * Defines the hardware scaling level.
  12521. * By default the hardware scaling level is computed from the window device ratio.
  12522. * 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.
  12523. * @param level defines the level to use
  12524. */
  12525. Engine.prototype.setHardwareScalingLevel = function (level) {
  12526. this._hardwareScalingLevel = level;
  12527. this.resize();
  12528. };
  12529. /**
  12530. * Gets the current hardware scaling level.
  12531. * By default the hardware scaling level is computed from the window device ratio.
  12532. * 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.
  12533. * @returns a number indicating the current hardware scaling level
  12534. */
  12535. Engine.prototype.getHardwareScalingLevel = function () {
  12536. return this._hardwareScalingLevel;
  12537. };
  12538. /**
  12539. * Gets the list of loaded textures
  12540. * @returns an array containing all loaded textures
  12541. */
  12542. Engine.prototype.getLoadedTexturesCache = function () {
  12543. return this._internalTexturesCache;
  12544. };
  12545. /**
  12546. * Gets the object containing all engine capabilities
  12547. * @returns the EngineCapabilities object
  12548. */
  12549. Engine.prototype.getCaps = function () {
  12550. return this._caps;
  12551. };
  12552. Object.defineProperty(Engine.prototype, "drawCalls", {
  12553. /** @hidden */
  12554. get: function () {
  12555. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12556. return 0;
  12557. },
  12558. enumerable: true,
  12559. configurable: true
  12560. });
  12561. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12562. /** @hidden */
  12563. get: function () {
  12564. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12565. return null;
  12566. },
  12567. enumerable: true,
  12568. configurable: true
  12569. });
  12570. /**
  12571. * Gets the current depth function
  12572. * @returns a number defining the depth function
  12573. */
  12574. Engine.prototype.getDepthFunction = function () {
  12575. return this._depthCullingState.depthFunc;
  12576. };
  12577. /**
  12578. * Sets the current depth function
  12579. * @param depthFunc defines the function to use
  12580. */
  12581. Engine.prototype.setDepthFunction = function (depthFunc) {
  12582. this._depthCullingState.depthFunc = depthFunc;
  12583. };
  12584. /**
  12585. * Sets the current depth function to GREATER
  12586. */
  12587. Engine.prototype.setDepthFunctionToGreater = function () {
  12588. this._depthCullingState.depthFunc = this._gl.GREATER;
  12589. };
  12590. /**
  12591. * Sets the current depth function to GEQUAL
  12592. */
  12593. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12594. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12595. };
  12596. /**
  12597. * Sets the current depth function to LESS
  12598. */
  12599. Engine.prototype.setDepthFunctionToLess = function () {
  12600. this._depthCullingState.depthFunc = this._gl.LESS;
  12601. };
  12602. /**
  12603. * Sets the current depth function to LEQUAL
  12604. */
  12605. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12606. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12607. };
  12608. /**
  12609. * Gets a boolean indicating if stencil buffer is enabled
  12610. * @returns the current stencil buffer state
  12611. */
  12612. Engine.prototype.getStencilBuffer = function () {
  12613. return this._stencilState.stencilTest;
  12614. };
  12615. /**
  12616. * Enable or disable the stencil buffer
  12617. * @param enable defines if the stencil buffer must be enabled or disabled
  12618. */
  12619. Engine.prototype.setStencilBuffer = function (enable) {
  12620. this._stencilState.stencilTest = enable;
  12621. };
  12622. /**
  12623. * Gets the current stencil mask
  12624. * @returns a number defining the new stencil mask to use
  12625. */
  12626. Engine.prototype.getStencilMask = function () {
  12627. return this._stencilState.stencilMask;
  12628. };
  12629. /**
  12630. * Sets the current stencil mask
  12631. * @param mask defines the new stencil mask to use
  12632. */
  12633. Engine.prototype.setStencilMask = function (mask) {
  12634. this._stencilState.stencilMask = mask;
  12635. };
  12636. /**
  12637. * Gets the current stencil function
  12638. * @returns a number defining the stencil function to use
  12639. */
  12640. Engine.prototype.getStencilFunction = function () {
  12641. return this._stencilState.stencilFunc;
  12642. };
  12643. /**
  12644. * Gets the current stencil reference value
  12645. * @returns a number defining the stencil reference value to use
  12646. */
  12647. Engine.prototype.getStencilFunctionReference = function () {
  12648. return this._stencilState.stencilFuncRef;
  12649. };
  12650. /**
  12651. * Gets the current stencil mask
  12652. * @returns a number defining the stencil mask to use
  12653. */
  12654. Engine.prototype.getStencilFunctionMask = function () {
  12655. return this._stencilState.stencilFuncMask;
  12656. };
  12657. /**
  12658. * Sets the current stencil function
  12659. * @param stencilFunc defines the new stencil function to use
  12660. */
  12661. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12662. this._stencilState.stencilFunc = stencilFunc;
  12663. };
  12664. /**
  12665. * Sets the current stencil reference
  12666. * @param reference defines the new stencil reference to use
  12667. */
  12668. Engine.prototype.setStencilFunctionReference = function (reference) {
  12669. this._stencilState.stencilFuncRef = reference;
  12670. };
  12671. /**
  12672. * Sets the current stencil mask
  12673. * @param mask defines the new stencil mask to use
  12674. */
  12675. Engine.prototype.setStencilFunctionMask = function (mask) {
  12676. this._stencilState.stencilFuncMask = mask;
  12677. };
  12678. /**
  12679. * Gets the current stencil operation when stencil fails
  12680. * @returns a number defining stencil operation to use when stencil fails
  12681. */
  12682. Engine.prototype.getStencilOperationFail = function () {
  12683. return this._stencilState.stencilOpStencilFail;
  12684. };
  12685. /**
  12686. * Gets the current stencil operation when depth fails
  12687. * @returns a number defining stencil operation to use when depth fails
  12688. */
  12689. Engine.prototype.getStencilOperationDepthFail = function () {
  12690. return this._stencilState.stencilOpDepthFail;
  12691. };
  12692. /**
  12693. * Gets the current stencil operation when stencil passes
  12694. * @returns a number defining stencil operation to use when stencil passes
  12695. */
  12696. Engine.prototype.getStencilOperationPass = function () {
  12697. return this._stencilState.stencilOpStencilDepthPass;
  12698. };
  12699. /**
  12700. * Sets the stencil operation to use when stencil fails
  12701. * @param operation defines the stencil operation to use when stencil fails
  12702. */
  12703. Engine.prototype.setStencilOperationFail = function (operation) {
  12704. this._stencilState.stencilOpStencilFail = operation;
  12705. };
  12706. /**
  12707. * Sets the stencil operation to use when depth fails
  12708. * @param operation defines the stencil operation to use when depth fails
  12709. */
  12710. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12711. this._stencilState.stencilOpDepthFail = operation;
  12712. };
  12713. /**
  12714. * Sets the stencil operation to use when stencil passes
  12715. * @param operation defines the stencil operation to use when stencil passes
  12716. */
  12717. Engine.prototype.setStencilOperationPass = function (operation) {
  12718. this._stencilState.stencilOpStencilDepthPass = operation;
  12719. };
  12720. /**
  12721. * Sets a boolean indicating if the dithering state is enabled or disabled
  12722. * @param value defines the dithering state
  12723. */
  12724. Engine.prototype.setDitheringState = function (value) {
  12725. if (value) {
  12726. this._gl.enable(this._gl.DITHER);
  12727. }
  12728. else {
  12729. this._gl.disable(this._gl.DITHER);
  12730. }
  12731. };
  12732. /**
  12733. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12734. * @param value defines the rasterizer state
  12735. */
  12736. Engine.prototype.setRasterizerState = function (value) {
  12737. if (value) {
  12738. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12739. }
  12740. else {
  12741. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12742. }
  12743. };
  12744. /**
  12745. * stop executing a render loop function and remove it from the execution array
  12746. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12747. */
  12748. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12749. if (!renderFunction) {
  12750. this._activeRenderLoops = [];
  12751. return;
  12752. }
  12753. var index = this._activeRenderLoops.indexOf(renderFunction);
  12754. if (index >= 0) {
  12755. this._activeRenderLoops.splice(index, 1);
  12756. }
  12757. };
  12758. /** @hidden */
  12759. Engine.prototype._renderLoop = function () {
  12760. if (!this._contextWasLost) {
  12761. var shouldRender = true;
  12762. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12763. shouldRender = false;
  12764. }
  12765. if (shouldRender) {
  12766. // Start new frame
  12767. this.beginFrame();
  12768. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12769. var renderFunction = this._activeRenderLoops[index];
  12770. renderFunction();
  12771. }
  12772. // Present
  12773. this.endFrame();
  12774. }
  12775. }
  12776. if (this._activeRenderLoops.length > 0) {
  12777. // Register new frame
  12778. var requester = null;
  12779. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12780. requester = this._vrDisplay;
  12781. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12782. }
  12783. else {
  12784. this._renderingQueueLaunched = false;
  12785. }
  12786. };
  12787. /**
  12788. * Register and execute a render loop. The engine can have more than one render function
  12789. * @param renderFunction defines the function to continuously execute
  12790. */
  12791. Engine.prototype.runRenderLoop = function (renderFunction) {
  12792. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12793. return;
  12794. }
  12795. this._activeRenderLoops.push(renderFunction);
  12796. if (!this._renderingQueueLaunched) {
  12797. this._renderingQueueLaunched = true;
  12798. this._bindedRenderFunction = this._renderLoop.bind(this);
  12799. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12800. }
  12801. };
  12802. /**
  12803. * Toggle full screen mode
  12804. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12805. * @param options defines an option object to be sent to the requestFullscreen function
  12806. */
  12807. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12808. if (this.isFullscreen) {
  12809. BABYLON.Tools.ExitFullscreen();
  12810. }
  12811. else {
  12812. this._pointerLockRequested = requestPointerLock;
  12813. if (this._renderingCanvas) {
  12814. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12815. }
  12816. }
  12817. };
  12818. /**
  12819. * Clear the current render buffer or the current render target (if any is set up)
  12820. * @param color defines the color to use
  12821. * @param backBuffer defines if the back buffer must be cleared
  12822. * @param depth defines if the depth buffer must be cleared
  12823. * @param stencil defines if the stencil buffer must be cleared
  12824. */
  12825. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12826. if (stencil === void 0) { stencil = false; }
  12827. this.applyStates();
  12828. var mode = 0;
  12829. if (backBuffer && color) {
  12830. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12831. mode |= this._gl.COLOR_BUFFER_BIT;
  12832. }
  12833. if (depth) {
  12834. this._gl.clearDepth(1.0);
  12835. mode |= this._gl.DEPTH_BUFFER_BIT;
  12836. }
  12837. if (stencil) {
  12838. this._gl.clearStencil(0);
  12839. mode |= this._gl.STENCIL_BUFFER_BIT;
  12840. }
  12841. this._gl.clear(mode);
  12842. };
  12843. /**
  12844. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12845. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12846. * @param y defines the y-coordinate of the corner of the clear rectangle
  12847. * @param width defines the width of the clear rectangle
  12848. * @param height defines the height of the clear rectangle
  12849. * @param clearColor defines the clear color
  12850. */
  12851. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12852. var gl = this._gl;
  12853. // Save state
  12854. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12855. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12856. // Change state
  12857. gl.enable(gl.SCISSOR_TEST);
  12858. gl.scissor(x, y, width, height);
  12859. // Clear
  12860. this.clear(clearColor, true, true, true);
  12861. // Restore state
  12862. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12863. if (curScissor === true) {
  12864. gl.enable(gl.SCISSOR_TEST);
  12865. }
  12866. else {
  12867. gl.disable(gl.SCISSOR_TEST);
  12868. }
  12869. };
  12870. /** @hidden */
  12871. Engine.prototype._viewport = function (x, y, width, height) {
  12872. if (x !== this._viewportCached.x ||
  12873. y !== this._viewportCached.y ||
  12874. width !== this._viewportCached.z ||
  12875. height !== this._viewportCached.w) {
  12876. this._viewportCached.x = x;
  12877. this._viewportCached.y = y;
  12878. this._viewportCached.z = width;
  12879. this._viewportCached.w = height;
  12880. this._gl.viewport(x, y, width, height);
  12881. }
  12882. };
  12883. /**
  12884. * Set the WebGL's viewport
  12885. * @param viewport defines the viewport element to be used
  12886. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12887. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12888. */
  12889. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12890. var width = requiredWidth || this.getRenderWidth();
  12891. var height = requiredHeight || this.getRenderHeight();
  12892. var x = viewport.x || 0;
  12893. var y = viewport.y || 0;
  12894. this._cachedViewport = viewport;
  12895. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12896. };
  12897. /**
  12898. * Directly set the WebGL Viewport
  12899. * @param x defines the x coordinate of the viewport (in screen space)
  12900. * @param y defines the y coordinate of the viewport (in screen space)
  12901. * @param width defines the width of the viewport (in screen space)
  12902. * @param height defines the height of the viewport (in screen space)
  12903. * @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
  12904. */
  12905. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12906. var currentViewport = this._cachedViewport;
  12907. this._cachedViewport = null;
  12908. this._viewport(x, y, width, height);
  12909. return currentViewport;
  12910. };
  12911. /**
  12912. * Begin a new frame
  12913. */
  12914. Engine.prototype.beginFrame = function () {
  12915. this.onBeginFrameObservable.notifyObservers(this);
  12916. this._measureFps();
  12917. };
  12918. /**
  12919. * Enf the current frame
  12920. */
  12921. Engine.prototype.endFrame = function () {
  12922. // Force a flush in case we are using a bad OS.
  12923. if (this._badOS) {
  12924. this.flushFramebuffer();
  12925. }
  12926. // Submit frame to the vr device, if enabled
  12927. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12928. // TODO: We should only submit the frame if we read frameData successfully.
  12929. this._vrDisplay.submitFrame();
  12930. }
  12931. this.onEndFrameObservable.notifyObservers(this);
  12932. };
  12933. /**
  12934. * Resize the view according to the canvas' size
  12935. */
  12936. Engine.prototype.resize = function () {
  12937. // We're not resizing the size of the canvas while in VR mode & presenting
  12938. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12939. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12940. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12941. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12942. }
  12943. };
  12944. /**
  12945. * Force a specific size of the canvas
  12946. * @param width defines the new canvas' width
  12947. * @param height defines the new canvas' height
  12948. */
  12949. Engine.prototype.setSize = function (width, height) {
  12950. if (!this._renderingCanvas) {
  12951. return;
  12952. }
  12953. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12954. return;
  12955. }
  12956. this._renderingCanvas.width = width;
  12957. this._renderingCanvas.height = height;
  12958. for (var index = 0; index < this.scenes.length; index++) {
  12959. var scene = this.scenes[index];
  12960. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12961. var cam = scene.cameras[camIndex];
  12962. cam._currentRenderId = 0;
  12963. }
  12964. }
  12965. if (this.onResizeObservable.hasObservers) {
  12966. this.onResizeObservable.notifyObservers(this);
  12967. }
  12968. };
  12969. // WebVR functions
  12970. /**
  12971. * Gets a boolean indicating if a webVR device was detected
  12972. * @returns true if a webVR device was detected
  12973. */
  12974. Engine.prototype.isVRDevicePresent = function () {
  12975. return !!this._vrDisplay;
  12976. };
  12977. /**
  12978. * Gets the current webVR device
  12979. * @returns the current webVR device (or null)
  12980. */
  12981. Engine.prototype.getVRDevice = function () {
  12982. return this._vrDisplay;
  12983. };
  12984. /**
  12985. * Initializes a webVR display and starts listening to display change events
  12986. * The onVRDisplayChangedObservable will be notified upon these changes
  12987. * @returns The onVRDisplayChangedObservable
  12988. */
  12989. Engine.prototype.initWebVR = function () {
  12990. this.initWebVRAsync();
  12991. return this.onVRDisplayChangedObservable;
  12992. };
  12993. /**
  12994. * Initializes a webVR display and starts listening to display change events
  12995. * The onVRDisplayChangedObservable will be notified upon these changes
  12996. * @returns A promise containing a VRDisplay and if vr is supported
  12997. */
  12998. Engine.prototype.initWebVRAsync = function () {
  12999. var _this = this;
  13000. var notifyObservers = function () {
  13001. var eventArgs = {
  13002. vrDisplay: _this._vrDisplay,
  13003. vrSupported: _this._vrSupported
  13004. };
  13005. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13006. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13007. };
  13008. if (!this._onVrDisplayConnect) {
  13009. this._onVrDisplayConnect = function (event) {
  13010. _this._vrDisplay = event.display;
  13011. notifyObservers();
  13012. };
  13013. this._onVrDisplayDisconnect = function () {
  13014. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13015. _this._vrDisplay = undefined;
  13016. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13017. notifyObservers();
  13018. };
  13019. this._onVrDisplayPresentChange = function () {
  13020. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13021. };
  13022. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13023. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13024. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13025. }
  13026. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13027. this._webVRInitPromise.then(notifyObservers);
  13028. return this._webVRInitPromise;
  13029. };
  13030. /**
  13031. * Call this function to switch to webVR mode
  13032. * Will do nothing if webVR is not supported or if there is no webVR device
  13033. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13034. */
  13035. Engine.prototype.enableVR = function () {
  13036. var _this = this;
  13037. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13038. var onResolved = function () {
  13039. _this.onVRRequestPresentComplete.notifyObservers(true);
  13040. _this._onVRFullScreenTriggered();
  13041. };
  13042. var onRejected = function () {
  13043. _this.onVRRequestPresentComplete.notifyObservers(false);
  13044. };
  13045. this.onVRRequestPresentStart.notifyObservers(this);
  13046. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13047. }
  13048. };
  13049. /**
  13050. * Call this function to leave webVR mode
  13051. * Will do nothing if webVR is not supported or if there is no webVR device
  13052. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13053. */
  13054. Engine.prototype.disableVR = function () {
  13055. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13056. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13057. }
  13058. };
  13059. Engine.prototype._getVRDisplaysAsync = function () {
  13060. var _this = this;
  13061. return new Promise(function (res, rej) {
  13062. if (navigator.getVRDisplays) {
  13063. navigator.getVRDisplays().then(function (devices) {
  13064. _this._vrSupported = true;
  13065. // note that devices may actually be an empty array. This is fine;
  13066. // we expect this._vrDisplay to be undefined in this case.
  13067. _this._vrDisplay = devices[0];
  13068. res({
  13069. vrDisplay: _this._vrDisplay,
  13070. vrSupported: _this._vrSupported
  13071. });
  13072. });
  13073. }
  13074. else {
  13075. _this._vrDisplay = undefined;
  13076. _this._vrSupported = false;
  13077. res({
  13078. vrDisplay: _this._vrDisplay,
  13079. vrSupported: _this._vrSupported
  13080. });
  13081. }
  13082. });
  13083. };
  13084. /**
  13085. * Binds the frame buffer to the specified texture.
  13086. * @param texture The texture to render to or null for the default canvas
  13087. * @param faceIndex The face of the texture to render to in case of cube texture
  13088. * @param requiredWidth The width of the target to render to
  13089. * @param requiredHeight The height of the target to render to
  13090. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13091. * @param depthStencilTexture The depth stencil texture to use to render
  13092. * @param lodLevel defines le lod level to bind to the frame buffer
  13093. */
  13094. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13095. if (lodLevel === void 0) { lodLevel = 0; }
  13096. if (this._currentRenderTarget) {
  13097. this.unBindFramebuffer(this._currentRenderTarget);
  13098. }
  13099. this._currentRenderTarget = texture;
  13100. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13101. var gl = this._gl;
  13102. if (texture.isCube) {
  13103. if (faceIndex === undefined) {
  13104. faceIndex = 0;
  13105. }
  13106. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13107. if (depthStencilTexture) {
  13108. if (depthStencilTexture._generateStencilBuffer) {
  13109. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13110. }
  13111. else {
  13112. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13113. }
  13114. }
  13115. }
  13116. if (this._cachedViewport && !forceFullscreenViewport) {
  13117. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13118. }
  13119. else {
  13120. if (!requiredWidth) {
  13121. requiredWidth = texture.width;
  13122. if (lodLevel) {
  13123. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13124. }
  13125. }
  13126. if (!requiredHeight) {
  13127. requiredHeight = texture.height;
  13128. if (lodLevel) {
  13129. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13130. }
  13131. }
  13132. this._viewport(0, 0, requiredWidth, requiredHeight);
  13133. }
  13134. this.wipeCaches();
  13135. };
  13136. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13137. if (this._currentFramebuffer !== framebuffer) {
  13138. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13139. this._currentFramebuffer = framebuffer;
  13140. }
  13141. };
  13142. /**
  13143. * Unbind the current render target texture from the webGL context
  13144. * @param texture defines the render target texture to unbind
  13145. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13146. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13147. */
  13148. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13149. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13150. this._currentRenderTarget = null;
  13151. // If MSAA, we need to bitblt back to main texture
  13152. var gl = this._gl;
  13153. if (texture._MSAAFramebuffer) {
  13154. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13155. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13156. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13157. }
  13158. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13159. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13160. gl.generateMipmap(gl.TEXTURE_2D);
  13161. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13162. }
  13163. if (onBeforeUnbind) {
  13164. if (texture._MSAAFramebuffer) {
  13165. // Bind the correct framebuffer
  13166. this.bindUnboundFramebuffer(texture._framebuffer);
  13167. }
  13168. onBeforeUnbind();
  13169. }
  13170. this.bindUnboundFramebuffer(null);
  13171. };
  13172. /**
  13173. * Unbind a list of render target textures from the webGL context
  13174. * This is used only when drawBuffer extension or webGL2 are active
  13175. * @param textures defines the render target textures to unbind
  13176. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13177. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13178. */
  13179. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13180. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13181. this._currentRenderTarget = null;
  13182. // If MSAA, we need to bitblt back to main texture
  13183. var gl = this._gl;
  13184. if (textures[0]._MSAAFramebuffer) {
  13185. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13186. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13187. var attachments = textures[0]._attachments;
  13188. if (!attachments) {
  13189. attachments = new Array(textures.length);
  13190. textures[0]._attachments = attachments;
  13191. }
  13192. for (var i = 0; i < textures.length; i++) {
  13193. var texture = textures[i];
  13194. for (var j = 0; j < attachments.length; j++) {
  13195. attachments[j] = gl.NONE;
  13196. }
  13197. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13198. gl.readBuffer(attachments[i]);
  13199. gl.drawBuffers(attachments);
  13200. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13201. }
  13202. for (var i = 0; i < attachments.length; i++) {
  13203. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13204. }
  13205. gl.drawBuffers(attachments);
  13206. }
  13207. for (var i = 0; i < textures.length; i++) {
  13208. var texture = textures[i];
  13209. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13210. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13211. gl.generateMipmap(gl.TEXTURE_2D);
  13212. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13213. }
  13214. }
  13215. if (onBeforeUnbind) {
  13216. if (textures[0]._MSAAFramebuffer) {
  13217. // Bind the correct framebuffer
  13218. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13219. }
  13220. onBeforeUnbind();
  13221. }
  13222. this.bindUnboundFramebuffer(null);
  13223. };
  13224. /**
  13225. * Force the mipmap generation for the given render target texture
  13226. * @param texture defines the render target texture to use
  13227. */
  13228. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13229. if (texture.generateMipMaps) {
  13230. var gl = this._gl;
  13231. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13232. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13233. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13234. }
  13235. };
  13236. /**
  13237. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13238. */
  13239. Engine.prototype.flushFramebuffer = function () {
  13240. this._gl.flush();
  13241. };
  13242. /**
  13243. * Unbind the current render target and bind the default framebuffer
  13244. */
  13245. Engine.prototype.restoreDefaultFramebuffer = function () {
  13246. if (this._currentRenderTarget) {
  13247. this.unBindFramebuffer(this._currentRenderTarget);
  13248. }
  13249. else {
  13250. this.bindUnboundFramebuffer(null);
  13251. }
  13252. if (this._cachedViewport) {
  13253. this.setViewport(this._cachedViewport);
  13254. }
  13255. this.wipeCaches();
  13256. };
  13257. // UBOs
  13258. /**
  13259. * Create an uniform buffer
  13260. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13261. * @param elements defines the content of the uniform buffer
  13262. * @returns the webGL uniform buffer
  13263. */
  13264. Engine.prototype.createUniformBuffer = function (elements) {
  13265. var ubo = this._gl.createBuffer();
  13266. if (!ubo) {
  13267. throw new Error("Unable to create uniform buffer");
  13268. }
  13269. this.bindUniformBuffer(ubo);
  13270. if (elements instanceof Float32Array) {
  13271. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13272. }
  13273. else {
  13274. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13275. }
  13276. this.bindUniformBuffer(null);
  13277. ubo.references = 1;
  13278. return ubo;
  13279. };
  13280. /**
  13281. * Create a dynamic uniform buffer
  13282. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13283. * @param elements defines the content of the uniform buffer
  13284. * @returns the webGL uniform buffer
  13285. */
  13286. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13287. var ubo = this._gl.createBuffer();
  13288. if (!ubo) {
  13289. throw new Error("Unable to create dynamic uniform buffer");
  13290. }
  13291. this.bindUniformBuffer(ubo);
  13292. if (elements instanceof Float32Array) {
  13293. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13294. }
  13295. else {
  13296. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13297. }
  13298. this.bindUniformBuffer(null);
  13299. ubo.references = 1;
  13300. return ubo;
  13301. };
  13302. /**
  13303. * Update an existing uniform buffer
  13304. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13305. * @param uniformBuffer defines the target uniform buffer
  13306. * @param elements defines the content to update
  13307. * @param offset defines the offset in the uniform buffer where update should start
  13308. * @param count defines the size of the data to update
  13309. */
  13310. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13311. this.bindUniformBuffer(uniformBuffer);
  13312. if (offset === undefined) {
  13313. offset = 0;
  13314. }
  13315. if (count === undefined) {
  13316. if (elements instanceof Float32Array) {
  13317. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13318. }
  13319. else {
  13320. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13321. }
  13322. }
  13323. else {
  13324. if (elements instanceof Float32Array) {
  13325. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13326. }
  13327. else {
  13328. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13329. }
  13330. }
  13331. this.bindUniformBuffer(null);
  13332. };
  13333. // VBOs
  13334. Engine.prototype._resetVertexBufferBinding = function () {
  13335. this.bindArrayBuffer(null);
  13336. this._cachedVertexBuffers = null;
  13337. };
  13338. /**
  13339. * Creates a vertex buffer
  13340. * @param data the data for the vertex buffer
  13341. * @returns the new WebGL static buffer
  13342. */
  13343. Engine.prototype.createVertexBuffer = function (data) {
  13344. var vbo = this._gl.createBuffer();
  13345. if (!vbo) {
  13346. throw new Error("Unable to create vertex buffer");
  13347. }
  13348. this.bindArrayBuffer(vbo);
  13349. if (data instanceof Array) {
  13350. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13351. }
  13352. else {
  13353. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13354. }
  13355. this._resetVertexBufferBinding();
  13356. vbo.references = 1;
  13357. return vbo;
  13358. };
  13359. /**
  13360. * Creates a dynamic vertex buffer
  13361. * @param data the data for the dynamic vertex buffer
  13362. * @returns the new WebGL dynamic buffer
  13363. */
  13364. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13365. var vbo = this._gl.createBuffer();
  13366. if (!vbo) {
  13367. throw new Error("Unable to create dynamic vertex buffer");
  13368. }
  13369. this.bindArrayBuffer(vbo);
  13370. if (data instanceof Array) {
  13371. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13372. }
  13373. else {
  13374. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13375. }
  13376. this._resetVertexBufferBinding();
  13377. vbo.references = 1;
  13378. return vbo;
  13379. };
  13380. /**
  13381. * Update a dynamic index buffer
  13382. * @param indexBuffer defines the target index buffer
  13383. * @param indices defines the data to update
  13384. * @param offset defines the offset in the target index buffer where update should start
  13385. */
  13386. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13387. if (offset === void 0) { offset = 0; }
  13388. // Force cache update
  13389. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13390. this.bindIndexBuffer(indexBuffer);
  13391. var arrayBuffer;
  13392. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13393. arrayBuffer = indices;
  13394. }
  13395. else {
  13396. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13397. }
  13398. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13399. this._resetIndexBufferBinding();
  13400. };
  13401. /**
  13402. * Updates a dynamic vertex buffer.
  13403. * @param vertexBuffer the vertex buffer to update
  13404. * @param data the data used to update the vertex buffer
  13405. * @param byteOffset the byte offset of the data
  13406. * @param byteLength the byte length of the data
  13407. */
  13408. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13409. this.bindArrayBuffer(vertexBuffer);
  13410. if (byteOffset === undefined) {
  13411. byteOffset = 0;
  13412. }
  13413. if (byteLength === undefined) {
  13414. if (data instanceof Array) {
  13415. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13416. }
  13417. else {
  13418. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13419. }
  13420. }
  13421. else {
  13422. if (data instanceof Array) {
  13423. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13424. }
  13425. else {
  13426. if (data instanceof ArrayBuffer) {
  13427. data = new Uint8Array(data, byteOffset, byteLength);
  13428. }
  13429. else {
  13430. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13431. }
  13432. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13433. }
  13434. }
  13435. this._resetVertexBufferBinding();
  13436. };
  13437. Engine.prototype._resetIndexBufferBinding = function () {
  13438. this.bindIndexBuffer(null);
  13439. this._cachedIndexBuffer = null;
  13440. };
  13441. /**
  13442. * Creates a new index buffer
  13443. * @param indices defines the content of the index buffer
  13444. * @param updatable defines if the index buffer must be updatable
  13445. * @returns a new webGL buffer
  13446. */
  13447. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13448. var vbo = this._gl.createBuffer();
  13449. if (!vbo) {
  13450. throw new Error("Unable to create index buffer");
  13451. }
  13452. this.bindIndexBuffer(vbo);
  13453. // Check for 32 bits indices
  13454. var arrayBuffer;
  13455. var need32Bits = false;
  13456. if (indices instanceof Uint16Array) {
  13457. arrayBuffer = indices;
  13458. }
  13459. else {
  13460. //check 32 bit support
  13461. if (this._caps.uintIndices) {
  13462. if (indices instanceof Uint32Array) {
  13463. arrayBuffer = indices;
  13464. need32Bits = true;
  13465. }
  13466. else {
  13467. //number[] or Int32Array, check if 32 bit is necessary
  13468. for (var index = 0; index < indices.length; index++) {
  13469. if (indices[index] > 65535) {
  13470. need32Bits = true;
  13471. break;
  13472. }
  13473. }
  13474. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13475. }
  13476. }
  13477. else {
  13478. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13479. arrayBuffer = new Uint16Array(indices);
  13480. }
  13481. }
  13482. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13483. this._resetIndexBufferBinding();
  13484. vbo.references = 1;
  13485. vbo.is32Bits = need32Bits;
  13486. return vbo;
  13487. };
  13488. /**
  13489. * Bind a webGL buffer to the webGL context
  13490. * @param buffer defines the buffer to bind
  13491. */
  13492. Engine.prototype.bindArrayBuffer = function (buffer) {
  13493. if (!this._vaoRecordInProgress) {
  13494. this._unbindVertexArrayObject();
  13495. }
  13496. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13497. };
  13498. /**
  13499. * Bind an uniform buffer to the current webGL context
  13500. * @param buffer defines the buffer to bind
  13501. */
  13502. Engine.prototype.bindUniformBuffer = function (buffer) {
  13503. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13504. };
  13505. /**
  13506. * Bind a buffer to the current webGL context at a given location
  13507. * @param buffer defines the buffer to bind
  13508. * @param location defines the index where to bind the buffer
  13509. */
  13510. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13511. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13512. };
  13513. /**
  13514. * Bind a specific block at a given index in a specific shader program
  13515. * @param shaderProgram defines the shader program
  13516. * @param blockName defines the block name
  13517. * @param index defines the index where to bind the block
  13518. */
  13519. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13520. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13521. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13522. };
  13523. ;
  13524. Engine.prototype.bindIndexBuffer = function (buffer) {
  13525. if (!this._vaoRecordInProgress) {
  13526. this._unbindVertexArrayObject();
  13527. }
  13528. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13529. };
  13530. Engine.prototype.bindBuffer = function (buffer, target) {
  13531. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13532. this._gl.bindBuffer(target, buffer);
  13533. this._currentBoundBuffer[target] = buffer;
  13534. }
  13535. };
  13536. /**
  13537. * update the bound buffer with the given data
  13538. * @param data defines the data to update
  13539. */
  13540. Engine.prototype.updateArrayBuffer = function (data) {
  13541. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13542. };
  13543. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13544. var pointer = this._currentBufferPointers[indx];
  13545. var changed = false;
  13546. if (!pointer.active) {
  13547. changed = true;
  13548. pointer.active = true;
  13549. pointer.index = indx;
  13550. pointer.size = size;
  13551. pointer.type = type;
  13552. pointer.normalized = normalized;
  13553. pointer.stride = stride;
  13554. pointer.offset = offset;
  13555. pointer.buffer = buffer;
  13556. }
  13557. else {
  13558. if (pointer.buffer !== buffer) {
  13559. pointer.buffer = buffer;
  13560. changed = true;
  13561. }
  13562. if (pointer.size !== size) {
  13563. pointer.size = size;
  13564. changed = true;
  13565. }
  13566. if (pointer.type !== type) {
  13567. pointer.type = type;
  13568. changed = true;
  13569. }
  13570. if (pointer.normalized !== normalized) {
  13571. pointer.normalized = normalized;
  13572. changed = true;
  13573. }
  13574. if (pointer.stride !== stride) {
  13575. pointer.stride = stride;
  13576. changed = true;
  13577. }
  13578. if (pointer.offset !== offset) {
  13579. pointer.offset = offset;
  13580. changed = true;
  13581. }
  13582. }
  13583. if (changed || this._vaoRecordInProgress) {
  13584. this.bindArrayBuffer(buffer);
  13585. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13586. }
  13587. };
  13588. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13589. if (indexBuffer == null) {
  13590. return;
  13591. }
  13592. if (this._cachedIndexBuffer !== indexBuffer) {
  13593. this._cachedIndexBuffer = indexBuffer;
  13594. this.bindIndexBuffer(indexBuffer);
  13595. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13596. }
  13597. };
  13598. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13599. var attributes = effect.getAttributesNames();
  13600. if (!this._vaoRecordInProgress) {
  13601. this._unbindVertexArrayObject();
  13602. }
  13603. this.unbindAllAttributes();
  13604. for (var index = 0; index < attributes.length; index++) {
  13605. var order = effect.getAttributeLocation(index);
  13606. if (order >= 0) {
  13607. var vertexBuffer = vertexBuffers[attributes[index]];
  13608. if (!vertexBuffer) {
  13609. continue;
  13610. }
  13611. this._gl.enableVertexAttribArray(order);
  13612. if (!this._vaoRecordInProgress) {
  13613. this._vertexAttribArraysEnabled[order] = true;
  13614. }
  13615. var buffer = vertexBuffer.getBuffer();
  13616. if (buffer) {
  13617. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13618. if (vertexBuffer.getIsInstanced()) {
  13619. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13620. if (!this._vaoRecordInProgress) {
  13621. this._currentInstanceLocations.push(order);
  13622. this._currentInstanceBuffers.push(buffer);
  13623. }
  13624. }
  13625. }
  13626. }
  13627. }
  13628. };
  13629. /**
  13630. * Records a vertex array object
  13631. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13632. * @param vertexBuffers defines the list of vertex buffers to store
  13633. * @param indexBuffer defines the index buffer to store
  13634. * @param effect defines the effect to store
  13635. * @returns the new vertex array object
  13636. */
  13637. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13638. var vao = this._gl.createVertexArray();
  13639. this._vaoRecordInProgress = true;
  13640. this._gl.bindVertexArray(vao);
  13641. this._mustWipeVertexAttributes = true;
  13642. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13643. this.bindIndexBuffer(indexBuffer);
  13644. this._vaoRecordInProgress = false;
  13645. this._gl.bindVertexArray(null);
  13646. return vao;
  13647. };
  13648. /**
  13649. * Bind a specific vertex array object
  13650. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13651. * @param vertexArrayObject defines the vertex array object to bind
  13652. * @param indexBuffer defines the index buffer to bind
  13653. */
  13654. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13655. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13656. this._cachedVertexArrayObject = vertexArrayObject;
  13657. this._gl.bindVertexArray(vertexArrayObject);
  13658. this._cachedVertexBuffers = null;
  13659. this._cachedIndexBuffer = null;
  13660. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13661. this._mustWipeVertexAttributes = true;
  13662. }
  13663. };
  13664. /**
  13665. * Bind webGl buffers directly to the webGL context
  13666. * @param vertexBuffer defines the vertex buffer to bind
  13667. * @param indexBuffer defines the index buffer to bind
  13668. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13669. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13670. * @param effect defines the effect associated with the vertex buffer
  13671. */
  13672. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13673. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13674. this._cachedVertexBuffers = vertexBuffer;
  13675. this._cachedEffectForVertexBuffers = effect;
  13676. var attributesCount = effect.getAttributesCount();
  13677. this._unbindVertexArrayObject();
  13678. this.unbindAllAttributes();
  13679. var offset = 0;
  13680. for (var index = 0; index < attributesCount; index++) {
  13681. if (index < vertexDeclaration.length) {
  13682. var order = effect.getAttributeLocation(index);
  13683. if (order >= 0) {
  13684. this._gl.enableVertexAttribArray(order);
  13685. this._vertexAttribArraysEnabled[order] = true;
  13686. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13687. }
  13688. offset += vertexDeclaration[index] * 4;
  13689. }
  13690. }
  13691. }
  13692. this._bindIndexBufferWithCache(indexBuffer);
  13693. };
  13694. Engine.prototype._unbindVertexArrayObject = function () {
  13695. if (!this._cachedVertexArrayObject) {
  13696. return;
  13697. }
  13698. this._cachedVertexArrayObject = null;
  13699. this._gl.bindVertexArray(null);
  13700. };
  13701. /**
  13702. * Bind a list of vertex buffers to the webGL context
  13703. * @param vertexBuffers defines the list of vertex buffers to bind
  13704. * @param indexBuffer defines the index buffer to bind
  13705. * @param effect defines the effect associated with the vertex buffers
  13706. */
  13707. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13708. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13709. this._cachedVertexBuffers = vertexBuffers;
  13710. this._cachedEffectForVertexBuffers = effect;
  13711. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13712. }
  13713. this._bindIndexBufferWithCache(indexBuffer);
  13714. };
  13715. /**
  13716. * Unbind all instance attributes
  13717. */
  13718. Engine.prototype.unbindInstanceAttributes = function () {
  13719. var boundBuffer;
  13720. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13721. var instancesBuffer = this._currentInstanceBuffers[i];
  13722. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13723. boundBuffer = instancesBuffer;
  13724. this.bindArrayBuffer(instancesBuffer);
  13725. }
  13726. var offsetLocation = this._currentInstanceLocations[i];
  13727. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13728. }
  13729. this._currentInstanceBuffers.length = 0;
  13730. this._currentInstanceLocations.length = 0;
  13731. };
  13732. /**
  13733. * Release and free the memory of a vertex array object
  13734. * @param vao defines the vertex array object to delete
  13735. */
  13736. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13737. this._gl.deleteVertexArray(vao);
  13738. };
  13739. /** @hidden */
  13740. Engine.prototype._releaseBuffer = function (buffer) {
  13741. buffer.references--;
  13742. if (buffer.references === 0) {
  13743. this._gl.deleteBuffer(buffer);
  13744. return true;
  13745. }
  13746. return false;
  13747. };
  13748. /**
  13749. * Creates a webGL buffer to use with instanciation
  13750. * @param capacity defines the size of the buffer
  13751. * @returns the webGL buffer
  13752. */
  13753. Engine.prototype.createInstancesBuffer = function (capacity) {
  13754. var buffer = this._gl.createBuffer();
  13755. if (!buffer) {
  13756. throw new Error("Unable to create instance buffer");
  13757. }
  13758. buffer.capacity = capacity;
  13759. this.bindArrayBuffer(buffer);
  13760. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13761. return buffer;
  13762. };
  13763. /**
  13764. * Delete a webGL buffer used with instanciation
  13765. * @param buffer defines the webGL buffer to delete
  13766. */
  13767. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13768. this._gl.deleteBuffer(buffer);
  13769. };
  13770. /**
  13771. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13772. * @param instancesBuffer defines the webGL buffer to update and bind
  13773. * @param data defines the data to store in the buffer
  13774. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13775. */
  13776. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13777. this.bindArrayBuffer(instancesBuffer);
  13778. if (data) {
  13779. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13780. }
  13781. if (offsetLocations[0].index !== undefined) {
  13782. var stride = 0;
  13783. for (var i = 0; i < offsetLocations.length; i++) {
  13784. var ai = offsetLocations[i];
  13785. stride += ai.attributeSize * 4;
  13786. }
  13787. for (var i = 0; i < offsetLocations.length; i++) {
  13788. var ai = offsetLocations[i];
  13789. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13790. this._gl.enableVertexAttribArray(ai.index);
  13791. this._vertexAttribArraysEnabled[ai.index] = true;
  13792. }
  13793. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13794. this._gl.vertexAttribDivisor(ai.index, 1);
  13795. this._currentInstanceLocations.push(ai.index);
  13796. this._currentInstanceBuffers.push(instancesBuffer);
  13797. }
  13798. }
  13799. else {
  13800. for (var index = 0; index < 4; index++) {
  13801. var offsetLocation = offsetLocations[index];
  13802. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13803. this._gl.enableVertexAttribArray(offsetLocation);
  13804. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13805. }
  13806. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13807. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13808. this._currentInstanceLocations.push(offsetLocation);
  13809. this._currentInstanceBuffers.push(instancesBuffer);
  13810. }
  13811. }
  13812. };
  13813. /**
  13814. * Apply all cached states (depth, culling, stencil and alpha)
  13815. */
  13816. Engine.prototype.applyStates = function () {
  13817. this._depthCullingState.apply(this._gl);
  13818. this._stencilState.apply(this._gl);
  13819. this._alphaState.apply(this._gl);
  13820. };
  13821. /**
  13822. * Send a draw order
  13823. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13824. * @param indexStart defines the starting index
  13825. * @param indexCount defines the number of index to draw
  13826. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13827. */
  13828. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13829. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13830. };
  13831. /**
  13832. * Draw a list of points
  13833. * @param verticesStart defines the index of first vertex to draw
  13834. * @param verticesCount defines the count of vertices to draw
  13835. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13836. */
  13837. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13838. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13839. };
  13840. /**
  13841. * Draw a list of unindexed primitives
  13842. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13843. * @param verticesStart defines the index of first vertex to draw
  13844. * @param verticesCount defines the count of vertices to draw
  13845. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13846. */
  13847. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13848. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13849. };
  13850. /**
  13851. * Draw a list of indexed primitives
  13852. * @param fillMode defines the primitive to use
  13853. * @param indexStart defines the starting index
  13854. * @param indexCount defines the number of index to draw
  13855. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13856. */
  13857. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13858. // Apply states
  13859. this.applyStates();
  13860. this._drawCalls.addCount(1, false);
  13861. // Render
  13862. var drawMode = this._drawMode(fillMode);
  13863. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13864. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13865. if (instancesCount) {
  13866. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13867. }
  13868. else {
  13869. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13870. }
  13871. };
  13872. /**
  13873. * Draw a list of unindexed primitives
  13874. * @param fillMode defines the primitive to use
  13875. * @param verticesStart defines the index of first vertex to draw
  13876. * @param verticesCount defines the count of vertices to draw
  13877. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13878. */
  13879. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13880. // Apply states
  13881. this.applyStates();
  13882. this._drawCalls.addCount(1, false);
  13883. var drawMode = this._drawMode(fillMode);
  13884. if (instancesCount) {
  13885. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13886. }
  13887. else {
  13888. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13889. }
  13890. };
  13891. Engine.prototype._drawMode = function (fillMode) {
  13892. switch (fillMode) {
  13893. // Triangle views
  13894. case BABYLON.Material.TriangleFillMode:
  13895. return this._gl.TRIANGLES;
  13896. case BABYLON.Material.PointFillMode:
  13897. return this._gl.POINTS;
  13898. case BABYLON.Material.WireFrameFillMode:
  13899. return this._gl.LINES;
  13900. // Draw modes
  13901. case BABYLON.Material.PointListDrawMode:
  13902. return this._gl.POINTS;
  13903. case BABYLON.Material.LineListDrawMode:
  13904. return this._gl.LINES;
  13905. case BABYLON.Material.LineLoopDrawMode:
  13906. return this._gl.LINE_LOOP;
  13907. case BABYLON.Material.LineStripDrawMode:
  13908. return this._gl.LINE_STRIP;
  13909. case BABYLON.Material.TriangleStripDrawMode:
  13910. return this._gl.TRIANGLE_STRIP;
  13911. case BABYLON.Material.TriangleFanDrawMode:
  13912. return this._gl.TRIANGLE_FAN;
  13913. default:
  13914. return this._gl.TRIANGLES;
  13915. }
  13916. };
  13917. // Shaders
  13918. /** @hidden */
  13919. Engine.prototype._releaseEffect = function (effect) {
  13920. if (this._compiledEffects[effect._key]) {
  13921. delete this._compiledEffects[effect._key];
  13922. this._deleteProgram(effect.getProgram());
  13923. }
  13924. };
  13925. /** @hidden */
  13926. Engine.prototype._deleteProgram = function (program) {
  13927. if (program) {
  13928. program.__SPECTOR_rebuildProgram = null;
  13929. if (program.transformFeedback) {
  13930. this.deleteTransformFeedback(program.transformFeedback);
  13931. program.transformFeedback = null;
  13932. }
  13933. this._gl.deleteProgram(program);
  13934. }
  13935. };
  13936. /**
  13937. * Create a new effect (used to store vertex/fragment shaders)
  13938. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13939. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13940. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13941. * @param samplers defines an array of string used to represent textures
  13942. * @param defines defines the string containing the defines to use to compile the shaders
  13943. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13944. * @param onCompiled defines a function to call when the effect creation is successful
  13945. * @param onError defines a function to call when the effect creation has failed
  13946. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13947. * @returns the new Effect
  13948. */
  13949. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13950. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13951. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13952. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13953. if (this._compiledEffects[name]) {
  13954. var compiledEffect = this._compiledEffects[name];
  13955. if (onCompiled && compiledEffect.isReady()) {
  13956. onCompiled(compiledEffect);
  13957. }
  13958. return compiledEffect;
  13959. }
  13960. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13961. effect._key = name;
  13962. this._compiledEffects[name] = effect;
  13963. return effect;
  13964. };
  13965. /**
  13966. * Create an effect to use with particle systems
  13967. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13968. * @param uniformsNames defines a list of attribute names
  13969. * @param samplers defines an array of string used to represent textures
  13970. * @param defines defines the string containing the defines to use to compile the shaders
  13971. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13972. * @param onCompiled defines a function to call when the effect creation is successful
  13973. * @param onError defines a function to call when the effect creation has failed
  13974. * @returns the new Effect
  13975. */
  13976. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13977. if (uniformsNames === void 0) { uniformsNames = []; }
  13978. if (samplers === void 0) { samplers = []; }
  13979. if (defines === void 0) { defines = ""; }
  13980. return this.createEffect({
  13981. vertex: "particles",
  13982. fragmentElement: fragmentName
  13983. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13984. };
  13985. /**
  13986. * Directly creates a webGL program
  13987. * @param vertexCode defines the vertex shader code to use
  13988. * @param fragmentCode defines the fragment shader code to use
  13989. * @param context defines the webGL context to use (if not set, the current one will be used)
  13990. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13991. * @returns the new webGL program
  13992. */
  13993. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13994. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13995. context = context || this._gl;
  13996. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13997. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13998. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13999. };
  14000. /**
  14001. * Creates a webGL program
  14002. * @param vertexCode defines the vertex shader code to use
  14003. * @param fragmentCode defines the fragment shader code to use
  14004. * @param defines defines the string containing the defines to use to compile the shaders
  14005. * @param context defines the webGL context to use (if not set, the current one will be used)
  14006. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14007. * @returns the new webGL program
  14008. */
  14009. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14010. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14011. context = context || this._gl;
  14012. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14013. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14014. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  14015. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  14016. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14017. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14018. return program;
  14019. };
  14020. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14021. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14022. var shaderProgram = context.createProgram();
  14023. if (!shaderProgram) {
  14024. throw new Error("Unable to create program");
  14025. }
  14026. context.attachShader(shaderProgram, vertexShader);
  14027. context.attachShader(shaderProgram, fragmentShader);
  14028. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14029. var transformFeedback = this.createTransformFeedback();
  14030. this.bindTransformFeedback(transformFeedback);
  14031. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14032. shaderProgram.transformFeedback = transformFeedback;
  14033. }
  14034. context.linkProgram(shaderProgram);
  14035. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14036. this.bindTransformFeedback(null);
  14037. }
  14038. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14039. if (!linked) {
  14040. context.validateProgram(shaderProgram);
  14041. var error = context.getProgramInfoLog(shaderProgram);
  14042. if (error) {
  14043. throw new Error(error);
  14044. }
  14045. }
  14046. context.deleteShader(vertexShader);
  14047. context.deleteShader(fragmentShader);
  14048. return shaderProgram;
  14049. };
  14050. /**
  14051. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14052. * @param shaderProgram defines the webGL program to use
  14053. * @param uniformsNames defines the list of uniform names
  14054. * @returns an array of webGL uniform locations
  14055. */
  14056. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14057. var results = new Array();
  14058. for (var index = 0; index < uniformsNames.length; index++) {
  14059. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14060. }
  14061. return results;
  14062. };
  14063. /**
  14064. * Gets the lsit of active attributes for a given webGL program
  14065. * @param shaderProgram defines the webGL program to use
  14066. * @param attributesNames defines the list of attribute names to get
  14067. * @returns an array of indices indicating the offset of each attribute
  14068. */
  14069. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14070. var results = [];
  14071. for (var index = 0; index < attributesNames.length; index++) {
  14072. try {
  14073. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14074. }
  14075. catch (e) {
  14076. results.push(-1);
  14077. }
  14078. }
  14079. return results;
  14080. };
  14081. /**
  14082. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14083. * @param effect defines the effect to activate
  14084. */
  14085. Engine.prototype.enableEffect = function (effect) {
  14086. if (!effect) {
  14087. return;
  14088. }
  14089. // Use program
  14090. this.bindSamplers(effect);
  14091. this._currentEffect = effect;
  14092. if (effect.onBind) {
  14093. effect.onBind(effect);
  14094. }
  14095. effect.onBindObservable.notifyObservers(effect);
  14096. };
  14097. /**
  14098. * Set the value of an uniform to an array of int32
  14099. * @param uniform defines the webGL uniform location where to store the value
  14100. * @param array defines the array of int32 to store
  14101. */
  14102. Engine.prototype.setIntArray = function (uniform, array) {
  14103. if (!uniform)
  14104. return;
  14105. this._gl.uniform1iv(uniform, array);
  14106. };
  14107. /**
  14108. * Set the value of an uniform to an array of int32 (stored as vec2)
  14109. * @param uniform defines the webGL uniform location where to store the value
  14110. * @param array defines the array of int32 to store
  14111. */
  14112. Engine.prototype.setIntArray2 = function (uniform, array) {
  14113. if (!uniform || array.length % 2 !== 0)
  14114. return;
  14115. this._gl.uniform2iv(uniform, array);
  14116. };
  14117. /**
  14118. * Set the value of an uniform to an array of int32 (stored as vec3)
  14119. * @param uniform defines the webGL uniform location where to store the value
  14120. * @param array defines the array of int32 to store
  14121. */
  14122. Engine.prototype.setIntArray3 = function (uniform, array) {
  14123. if (!uniform || array.length % 3 !== 0)
  14124. return;
  14125. this._gl.uniform3iv(uniform, array);
  14126. };
  14127. /**
  14128. * Set the value of an uniform to an array of int32 (stored as vec4)
  14129. * @param uniform defines the webGL uniform location where to store the value
  14130. * @param array defines the array of int32 to store
  14131. */
  14132. Engine.prototype.setIntArray4 = function (uniform, array) {
  14133. if (!uniform || array.length % 4 !== 0)
  14134. return;
  14135. this._gl.uniform4iv(uniform, array);
  14136. };
  14137. /**
  14138. * Set the value of an uniform to an array of float32
  14139. * @param uniform defines the webGL uniform location where to store the value
  14140. * @param array defines the array of float32 to store
  14141. */
  14142. Engine.prototype.setFloatArray = function (uniform, array) {
  14143. if (!uniform)
  14144. return;
  14145. this._gl.uniform1fv(uniform, array);
  14146. };
  14147. /**
  14148. * Set the value of an uniform to an array of float32 (stored as vec2)
  14149. * @param uniform defines the webGL uniform location where to store the value
  14150. * @param array defines the array of float32 to store
  14151. */
  14152. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14153. if (!uniform || array.length % 2 !== 0)
  14154. return;
  14155. this._gl.uniform2fv(uniform, array);
  14156. };
  14157. /**
  14158. * Set the value of an uniform to an array of float32 (stored as vec3)
  14159. * @param uniform defines the webGL uniform location where to store the value
  14160. * @param array defines the array of float32 to store
  14161. */
  14162. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14163. if (!uniform || array.length % 3 !== 0)
  14164. return;
  14165. this._gl.uniform3fv(uniform, array);
  14166. };
  14167. /**
  14168. * Set the value of an uniform to an array of float32 (stored as vec4)
  14169. * @param uniform defines the webGL uniform location where to store the value
  14170. * @param array defines the array of float32 to store
  14171. */
  14172. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14173. if (!uniform || array.length % 4 !== 0)
  14174. return;
  14175. this._gl.uniform4fv(uniform, array);
  14176. };
  14177. /**
  14178. * Set the value of an uniform to an array of number
  14179. * @param uniform defines the webGL uniform location where to store the value
  14180. * @param array defines the array of number to store
  14181. */
  14182. Engine.prototype.setArray = function (uniform, array) {
  14183. if (!uniform)
  14184. return;
  14185. this._gl.uniform1fv(uniform, array);
  14186. };
  14187. /**
  14188. * Set the value of an uniform to an array of number (stored as vec2)
  14189. * @param uniform defines the webGL uniform location where to store the value
  14190. * @param array defines the array of number to store
  14191. */
  14192. Engine.prototype.setArray2 = function (uniform, array) {
  14193. if (!uniform || array.length % 2 !== 0)
  14194. return;
  14195. this._gl.uniform2fv(uniform, array);
  14196. };
  14197. /**
  14198. * Set the value of an uniform to an array of number (stored as vec3)
  14199. * @param uniform defines the webGL uniform location where to store the value
  14200. * @param array defines the array of number to store
  14201. */
  14202. Engine.prototype.setArray3 = function (uniform, array) {
  14203. if (!uniform || array.length % 3 !== 0)
  14204. return;
  14205. this._gl.uniform3fv(uniform, array);
  14206. };
  14207. /**
  14208. * Set the value of an uniform to an array of number (stored as vec4)
  14209. * @param uniform defines the webGL uniform location where to store the value
  14210. * @param array defines the array of number to store
  14211. */
  14212. Engine.prototype.setArray4 = function (uniform, array) {
  14213. if (!uniform || array.length % 4 !== 0)
  14214. return;
  14215. this._gl.uniform4fv(uniform, array);
  14216. };
  14217. /**
  14218. * Set the value of an uniform to an array of float32 (stored as matrices)
  14219. * @param uniform defines the webGL uniform location where to store the value
  14220. * @param matrices defines the array of float32 to store
  14221. */
  14222. Engine.prototype.setMatrices = function (uniform, matrices) {
  14223. if (!uniform)
  14224. return;
  14225. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14226. };
  14227. /**
  14228. * Set the value of an uniform to a matrix
  14229. * @param uniform defines the webGL uniform location where to store the value
  14230. * @param matrix defines the matrix to store
  14231. */
  14232. Engine.prototype.setMatrix = function (uniform, matrix) {
  14233. if (!uniform)
  14234. return;
  14235. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14236. };
  14237. /**
  14238. * Set the value of an uniform to a matrix (3x3)
  14239. * @param uniform defines the webGL uniform location where to store the value
  14240. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14241. */
  14242. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14243. if (!uniform)
  14244. return;
  14245. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14246. };
  14247. /**
  14248. * Set the value of an uniform to a matrix (2x2)
  14249. * @param uniform defines the webGL uniform location where to store the value
  14250. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14251. */
  14252. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14253. if (!uniform)
  14254. return;
  14255. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14256. };
  14257. /**
  14258. * Set the value of an uniform to a number (int)
  14259. * @param uniform defines the webGL uniform location where to store the value
  14260. * @param value defines the int number to store
  14261. */
  14262. Engine.prototype.setInt = function (uniform, value) {
  14263. if (!uniform)
  14264. return;
  14265. this._gl.uniform1i(uniform, value);
  14266. };
  14267. /**
  14268. * Set the value of an uniform to a number (float)
  14269. * @param uniform defines the webGL uniform location where to store the value
  14270. * @param value defines the float number to store
  14271. */
  14272. Engine.prototype.setFloat = function (uniform, value) {
  14273. if (!uniform)
  14274. return;
  14275. this._gl.uniform1f(uniform, value);
  14276. };
  14277. /**
  14278. * Set the value of an uniform to a vec2
  14279. * @param uniform defines the webGL uniform location where to store the value
  14280. * @param x defines the 1st component of the value
  14281. * @param y defines the 2nd component of the value
  14282. */
  14283. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14284. if (!uniform)
  14285. return;
  14286. this._gl.uniform2f(uniform, x, y);
  14287. };
  14288. /**
  14289. * Set the value of an uniform to a vec3
  14290. * @param uniform defines the webGL uniform location where to store the value
  14291. * @param x defines the 1st component of the value
  14292. * @param y defines the 2nd component of the value
  14293. * @param z defines the 3rd component of the value
  14294. */
  14295. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14296. if (!uniform)
  14297. return;
  14298. this._gl.uniform3f(uniform, x, y, z);
  14299. };
  14300. /**
  14301. * Set the value of an uniform to a boolean
  14302. * @param uniform defines the webGL uniform location where to store the value
  14303. * @param bool defines the boolean to store
  14304. */
  14305. Engine.prototype.setBool = function (uniform, bool) {
  14306. if (!uniform)
  14307. return;
  14308. this._gl.uniform1i(uniform, bool);
  14309. };
  14310. /**
  14311. * Set the value of an uniform to a vec4
  14312. * @param uniform defines the webGL uniform location where to store the value
  14313. * @param x defines the 1st component of the value
  14314. * @param y defines the 2nd component of the value
  14315. * @param z defines the 3rd component of the value
  14316. * @param w defines the 4th component of the value
  14317. */
  14318. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14319. if (!uniform)
  14320. return;
  14321. this._gl.uniform4f(uniform, x, y, z, w);
  14322. };
  14323. /**
  14324. * Set the value of an uniform to a Color3
  14325. * @param uniform defines the webGL uniform location where to store the value
  14326. * @param color3 defines the color to store
  14327. */
  14328. Engine.prototype.setColor3 = function (uniform, color3) {
  14329. if (!uniform)
  14330. return;
  14331. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14332. };
  14333. /**
  14334. * Set the value of an uniform to a Color3 and an alpha value
  14335. * @param uniform defines the webGL uniform location where to store the value
  14336. * @param color3 defines the color to store
  14337. * @param alpha defines the alpha component to store
  14338. */
  14339. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14340. if (!uniform)
  14341. return;
  14342. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14343. };
  14344. /**
  14345. * Sets a Color4 on a uniform variable
  14346. * @param uniform defines the uniform location
  14347. * @param color4 defines the value to be set
  14348. */
  14349. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14350. if (!uniform)
  14351. return;
  14352. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14353. };
  14354. // States
  14355. /**
  14356. * Set various states to the webGL context
  14357. * @param culling defines backface culling state
  14358. * @param zOffset defines the value to apply to zOffset (0 by default)
  14359. * @param force defines if states must be applied even if cache is up to date
  14360. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14361. */
  14362. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14363. if (zOffset === void 0) { zOffset = 0; }
  14364. if (reverseSide === void 0) { reverseSide = false; }
  14365. // Culling
  14366. if (this._depthCullingState.cull !== culling || force) {
  14367. this._depthCullingState.cull = culling;
  14368. }
  14369. // Cull face
  14370. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14371. if (this._depthCullingState.cullFace !== cullFace || force) {
  14372. this._depthCullingState.cullFace = cullFace;
  14373. }
  14374. // Z offset
  14375. this.setZOffset(zOffset);
  14376. // Front face
  14377. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14378. if (this._depthCullingState.frontFace !== frontFace || force) {
  14379. this._depthCullingState.frontFace = frontFace;
  14380. }
  14381. };
  14382. /**
  14383. * Set the z offset to apply to current rendering
  14384. * @param value defines the offset to apply
  14385. */
  14386. Engine.prototype.setZOffset = function (value) {
  14387. this._depthCullingState.zOffset = value;
  14388. };
  14389. /**
  14390. * Gets the current value of the zOffset
  14391. * @returns the current zOffset state
  14392. */
  14393. Engine.prototype.getZOffset = function () {
  14394. return this._depthCullingState.zOffset;
  14395. };
  14396. /**
  14397. * Enable or disable depth buffering
  14398. * @param enable defines the state to set
  14399. */
  14400. Engine.prototype.setDepthBuffer = function (enable) {
  14401. this._depthCullingState.depthTest = enable;
  14402. };
  14403. /**
  14404. * Gets a boolean indicating if depth writing is enabled
  14405. * @returns the current depth writing state
  14406. */
  14407. Engine.prototype.getDepthWrite = function () {
  14408. return this._depthCullingState.depthMask;
  14409. };
  14410. /**
  14411. * Enable or disable depth writing
  14412. * @param enable defines the state to set
  14413. */
  14414. Engine.prototype.setDepthWrite = function (enable) {
  14415. this._depthCullingState.depthMask = enable;
  14416. };
  14417. /**
  14418. * Enable or disable color writing
  14419. * @param enable defines the state to set
  14420. */
  14421. Engine.prototype.setColorWrite = function (enable) {
  14422. this._gl.colorMask(enable, enable, enable, enable);
  14423. this._colorWrite = enable;
  14424. };
  14425. /**
  14426. * Gets a boolean indicating if color writing is enabled
  14427. * @returns the current color writing state
  14428. */
  14429. Engine.prototype.getColorWrite = function () {
  14430. return this._colorWrite;
  14431. };
  14432. /**
  14433. * Sets alpha constants used by some alpha blending modes
  14434. * @param r defines the red component
  14435. * @param g defines the green component
  14436. * @param b defines the blue component
  14437. * @param a defines the alpha component
  14438. */
  14439. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14440. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14441. };
  14442. /**
  14443. * Sets the current alpha mode
  14444. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14445. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14446. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14447. */
  14448. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14449. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14450. if (this._alphaMode === mode) {
  14451. return;
  14452. }
  14453. switch (mode) {
  14454. case Engine.ALPHA_DISABLE:
  14455. this._alphaState.alphaBlend = false;
  14456. break;
  14457. case Engine.ALPHA_PREMULTIPLIED:
  14458. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14459. this._alphaState.alphaBlend = true;
  14460. break;
  14461. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14462. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14463. this._alphaState.alphaBlend = true;
  14464. break;
  14465. case Engine.ALPHA_COMBINE:
  14466. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14467. this._alphaState.alphaBlend = true;
  14468. break;
  14469. case Engine.ALPHA_ONEONE:
  14470. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14471. this._alphaState.alphaBlend = true;
  14472. break;
  14473. case Engine.ALPHA_ADD:
  14474. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14475. this._alphaState.alphaBlend = true;
  14476. break;
  14477. case Engine.ALPHA_SUBTRACT:
  14478. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14479. this._alphaState.alphaBlend = true;
  14480. break;
  14481. case Engine.ALPHA_MULTIPLY:
  14482. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14483. this._alphaState.alphaBlend = true;
  14484. break;
  14485. case Engine.ALPHA_MAXIMIZED:
  14486. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14487. this._alphaState.alphaBlend = true;
  14488. break;
  14489. case Engine.ALPHA_INTERPOLATE:
  14490. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14491. this._alphaState.alphaBlend = true;
  14492. break;
  14493. case Engine.ALPHA_SCREENMODE:
  14494. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14495. this._alphaState.alphaBlend = true;
  14496. break;
  14497. }
  14498. if (!noDepthWriteChange) {
  14499. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14500. }
  14501. this._alphaMode = mode;
  14502. };
  14503. /**
  14504. * Gets the current alpha mode
  14505. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14506. * @returns the current alpha mode
  14507. */
  14508. Engine.prototype.getAlphaMode = function () {
  14509. return this._alphaMode;
  14510. };
  14511. // Textures
  14512. /**
  14513. * Clears the list of texture accessible through engine.
  14514. * This can help preventing texture load conflict due to name collision.
  14515. */
  14516. Engine.prototype.clearInternalTexturesCache = function () {
  14517. this._internalTexturesCache = [];
  14518. };
  14519. /**
  14520. * Force the entire cache to be cleared
  14521. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14522. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14523. */
  14524. Engine.prototype.wipeCaches = function (bruteForce) {
  14525. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14526. return;
  14527. }
  14528. this._currentEffect = null;
  14529. this._unpackFlipYCached = null;
  14530. this._viewportCached.x = 0;
  14531. this._viewportCached.y = 0;
  14532. this._viewportCached.z = 0;
  14533. this._viewportCached.w = 0;
  14534. if (bruteForce) {
  14535. this.resetTextureCache();
  14536. this._currentProgram = null;
  14537. this._stencilState.reset();
  14538. this._depthCullingState.reset();
  14539. this.setDepthFunctionToLessOrEqual();
  14540. this._alphaState.reset();
  14541. }
  14542. this._resetVertexBufferBinding();
  14543. this._cachedIndexBuffer = null;
  14544. this._cachedEffectForVertexBuffers = null;
  14545. this._unbindVertexArrayObject();
  14546. this.bindIndexBuffer(null);
  14547. };
  14548. /**
  14549. * Set the compressed texture format to use, based on the formats you have, and the formats
  14550. * supported by the hardware / browser.
  14551. *
  14552. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14553. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14554. * to API arguments needed to compressed textures. This puts the burden on the container
  14555. * generator to house the arcane code for determining these for current & future formats.
  14556. *
  14557. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14558. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14559. *
  14560. * Note: The result of this call is not taken into account when a texture is base64.
  14561. *
  14562. * @param formatsAvailable defines the list of those format families you have created
  14563. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14564. *
  14565. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14566. * @returns The extension selected.
  14567. */
  14568. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14569. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14570. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14571. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14572. return this._textureFormatInUse = this._texturesSupported[i];
  14573. }
  14574. }
  14575. }
  14576. // actively set format to nothing, to allow this to be called more than once
  14577. // and possibly fail the 2nd time
  14578. this._textureFormatInUse = null;
  14579. return null;
  14580. };
  14581. /** @hidden */
  14582. Engine.prototype._createTexture = function () {
  14583. var texture = this._gl.createTexture();
  14584. if (!texture) {
  14585. throw new Error("Unable to create texture");
  14586. }
  14587. return texture;
  14588. };
  14589. /**
  14590. * Usually called from BABYLON.Texture.ts.
  14591. * Passed information to create a WebGLTexture
  14592. * @param urlArg defines a value which contains one of the following:
  14593. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14594. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14595. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14596. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14597. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14598. * @param scene needed for loading to the correct scene
  14599. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14600. * @param onLoad optional callback to be called upon successful completion
  14601. * @param onError optional callback to be called upon failure
  14602. * @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
  14603. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14604. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14605. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14606. */
  14607. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14608. var _this = this;
  14609. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14610. if (onLoad === void 0) { onLoad = null; }
  14611. if (onError === void 0) { onError = null; }
  14612. if (buffer === void 0) { buffer = null; }
  14613. if (fallback === void 0) { fallback = null; }
  14614. if (format === void 0) { format = null; }
  14615. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14616. var fromData = url.substr(0, 5) === "data:";
  14617. var fromBlob = url.substr(0, 5) === "blob:";
  14618. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14619. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14620. // establish the file extension, if possible
  14621. var lastDot = url.lastIndexOf('.');
  14622. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14623. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14624. var isTGA = (extension.indexOf(".tga") === 0);
  14625. // determine if a ktx file should be substituted
  14626. var isKTX = false;
  14627. if (this._textureFormatInUse && !isBase64 && !fallback && !buffer) {
  14628. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14629. isKTX = true;
  14630. }
  14631. if (scene) {
  14632. scene._addPendingData(texture);
  14633. }
  14634. texture.url = url;
  14635. texture.generateMipMaps = !noMipmap;
  14636. texture.samplingMode = samplingMode;
  14637. texture.invertY = invertY;
  14638. if (!this._doNotHandleContextLost) {
  14639. // Keep a link to the buffer only if we plan to handle context lost
  14640. texture._buffer = buffer;
  14641. }
  14642. var onLoadObserver = null;
  14643. if (onLoad && !fallback) {
  14644. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14645. }
  14646. if (!fallback)
  14647. this._internalTexturesCache.push(texture);
  14648. var onerror = function (message, exception) {
  14649. if (scene) {
  14650. scene._removePendingData(texture);
  14651. }
  14652. if (onLoadObserver && !isKTX) {
  14653. //dont remove the observer if its a ktx file, since the fallback createTexture call will require it.
  14654. texture.onLoadedObservable.remove(onLoadObserver);
  14655. }
  14656. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14657. if (isKTX) {
  14658. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14659. }
  14660. else if (BABYLON.Tools.UseFallbackTexture) {
  14661. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14662. }
  14663. if (onError) {
  14664. onError(message || "Unknown error", exception);
  14665. }
  14666. };
  14667. var callback = null;
  14668. // processing for non-image formats
  14669. if (isKTX || isTGA || isDDS) {
  14670. if (isKTX) {
  14671. callback = function (data) {
  14672. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14673. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14674. ktx.uploadLevels(_this._gl, !noMipmap);
  14675. return false;
  14676. }, samplingMode);
  14677. };
  14678. }
  14679. else if (isTGA) {
  14680. callback = function (arrayBuffer) {
  14681. var data = new Uint8Array(arrayBuffer);
  14682. var header = BABYLON.TGATools.GetTGAHeader(data);
  14683. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14684. BABYLON.TGATools.UploadContent(_this._gl, data);
  14685. return false;
  14686. }, samplingMode);
  14687. };
  14688. }
  14689. else if (isDDS) {
  14690. callback = function (data) {
  14691. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14692. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14693. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14694. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14695. return false;
  14696. }, samplingMode);
  14697. };
  14698. }
  14699. if (!buffer) {
  14700. this._loadFile(url, function (data) {
  14701. if (callback) {
  14702. callback(data);
  14703. }
  14704. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14705. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14706. });
  14707. }
  14708. else {
  14709. if (callback) {
  14710. callback(buffer);
  14711. }
  14712. }
  14713. // image format processing
  14714. }
  14715. else {
  14716. var onload = function (img) {
  14717. if (fromBlob && !_this._doNotHandleContextLost) {
  14718. // We need to store the image if we need to rebuild the texture
  14719. // in case of a webgl context lost
  14720. texture._buffer = img;
  14721. }
  14722. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14723. var gl = _this._gl;
  14724. var isPot = (img.width === potWidth && img.height === potHeight);
  14725. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14726. if (isPot) {
  14727. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14728. return false;
  14729. }
  14730. // Using shaders to rescale because canvas.drawImage is lossy
  14731. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14732. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14733. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14734. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14735. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14736. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14737. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14738. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14739. _this._releaseTexture(source);
  14740. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14741. continuationCallback();
  14742. });
  14743. return true;
  14744. }, samplingMode);
  14745. };
  14746. if (!fromData || isBase64) {
  14747. if (buffer instanceof HTMLImageElement) {
  14748. onload(buffer);
  14749. }
  14750. else {
  14751. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14752. }
  14753. }
  14754. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14755. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14756. }
  14757. else {
  14758. onload(buffer);
  14759. }
  14760. }
  14761. return texture;
  14762. };
  14763. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14764. var _this = this;
  14765. var rtt = this.createRenderTargetTexture({
  14766. width: destination.width,
  14767. height: destination.height,
  14768. }, {
  14769. generateMipMaps: false,
  14770. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14771. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14772. generateDepthBuffer: false,
  14773. generateStencilBuffer: false
  14774. });
  14775. if (!this._rescalePostProcess) {
  14776. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14777. }
  14778. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14779. _this._rescalePostProcess.onApply = function (effect) {
  14780. effect._bindTexture("textureSampler", source);
  14781. };
  14782. var hostingScene = scene;
  14783. if (!hostingScene) {
  14784. hostingScene = _this.scenes[_this.scenes.length - 1];
  14785. }
  14786. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14787. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14788. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14789. _this.unBindFramebuffer(rtt);
  14790. _this._releaseTexture(rtt);
  14791. if (onComplete) {
  14792. onComplete();
  14793. }
  14794. });
  14795. };
  14796. /**
  14797. * Update a raw texture
  14798. * @param texture defines the texture to update
  14799. * @param data defines the data to store in the texture
  14800. * @param format defines the format of the data
  14801. * @param invertY defines if data must be stored with Y axis inverted
  14802. * @param compression defines the compression used (null by default)
  14803. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14804. */
  14805. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14806. if (compression === void 0) { compression = null; }
  14807. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14808. if (!texture) {
  14809. return;
  14810. }
  14811. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14812. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14813. // babylon's internalFormat but gl's texImage2D format
  14814. var internalFormat = this._getInternalFormat(format);
  14815. var textureType = this._getWebGLTextureType(type);
  14816. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14817. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14818. if (!this._doNotHandleContextLost) {
  14819. texture._bufferView = data;
  14820. texture.format = format;
  14821. texture.type = type;
  14822. texture.invertY = invertY;
  14823. texture._compression = compression;
  14824. }
  14825. if (texture.width % 4 !== 0) {
  14826. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14827. }
  14828. if (compression && data) {
  14829. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14830. }
  14831. else {
  14832. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14833. }
  14834. if (texture.generateMipMaps) {
  14835. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14836. }
  14837. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14838. // this.resetTextureCache();
  14839. texture.isReady = true;
  14840. };
  14841. /**
  14842. * Creates a raw texture
  14843. * @param data defines the data to store in the texture
  14844. * @param width defines the width of the texture
  14845. * @param height defines the height of the texture
  14846. * @param format defines the format of the data
  14847. * @param generateMipMaps defines if the engine should generate the mip levels
  14848. * @param invertY defines if data must be stored with Y axis inverted
  14849. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14850. * @param compression defines the compression used (null by default)
  14851. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14852. * @returns the raw texture inside an InternalTexture
  14853. */
  14854. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14855. if (compression === void 0) { compression = null; }
  14856. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14857. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14858. texture.baseWidth = width;
  14859. texture.baseHeight = height;
  14860. texture.width = width;
  14861. texture.height = height;
  14862. texture.format = format;
  14863. texture.generateMipMaps = generateMipMaps;
  14864. texture.samplingMode = samplingMode;
  14865. texture.invertY = invertY;
  14866. texture._compression = compression;
  14867. texture.type = type;
  14868. if (!this._doNotHandleContextLost) {
  14869. texture._bufferView = data;
  14870. }
  14871. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14872. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14873. // Filters
  14874. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14875. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14876. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14877. if (generateMipMaps) {
  14878. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14879. }
  14880. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14881. this._internalTexturesCache.push(texture);
  14882. return texture;
  14883. };
  14884. /** @hidden */
  14885. Engine.prototype._unpackFlipY = function (value) {
  14886. if (this._unpackFlipYCached !== value) {
  14887. this._unpackFlipYCached = value;
  14888. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14889. }
  14890. };
  14891. /**
  14892. * Creates a dynamic texture
  14893. * @param width defines the width of the texture
  14894. * @param height defines the height of the texture
  14895. * @param generateMipMaps defines if the engine should generate the mip levels
  14896. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14897. * @returns the dynamic texture inside an InternalTexture
  14898. */
  14899. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14900. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14901. texture.baseWidth = width;
  14902. texture.baseHeight = height;
  14903. if (generateMipMaps) {
  14904. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14905. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14906. }
  14907. // this.resetTextureCache();
  14908. texture.width = width;
  14909. texture.height = height;
  14910. texture.isReady = false;
  14911. texture.generateMipMaps = generateMipMaps;
  14912. texture.samplingMode = samplingMode;
  14913. this.updateTextureSamplingMode(samplingMode, texture);
  14914. this._internalTexturesCache.push(texture);
  14915. return texture;
  14916. };
  14917. /**
  14918. * Update the sampling mode of a given texture
  14919. * @param samplingMode defines the required sampling mode
  14920. * @param texture defines the texture to update
  14921. */
  14922. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14923. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14924. if (texture.isCube) {
  14925. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14926. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14927. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14928. }
  14929. else if (texture.is3D) {
  14930. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14931. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14932. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14933. }
  14934. else {
  14935. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14936. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14937. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14938. }
  14939. texture.samplingMode = samplingMode;
  14940. };
  14941. /**
  14942. * Update the content of a dynamic texture
  14943. * @param texture defines the texture to update
  14944. * @param canvas defines the canvas containing the source
  14945. * @param invertY defines if data must be stored with Y axis inverted
  14946. * @param premulAlpha defines if alpha is stored as premultiplied
  14947. * @param format defines the format of the data
  14948. */
  14949. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14950. if (premulAlpha === void 0) { premulAlpha = false; }
  14951. if (!texture) {
  14952. return;
  14953. }
  14954. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14955. this._unpackFlipY(invertY);
  14956. if (premulAlpha) {
  14957. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14958. }
  14959. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14960. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14961. if (texture.generateMipMaps) {
  14962. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14963. }
  14964. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14965. if (premulAlpha) {
  14966. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14967. }
  14968. texture.isReady = true;
  14969. };
  14970. /**
  14971. * Update a video texture
  14972. * @param texture defines the texture to update
  14973. * @param video defines the video element to use
  14974. * @param invertY defines if data must be stored with Y axis inverted
  14975. */
  14976. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14977. if (!texture || texture._isDisabled) {
  14978. return;
  14979. }
  14980. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14981. this._unpackFlipY(!invertY); // Video are upside down by default
  14982. try {
  14983. // Testing video texture support
  14984. if (this._videoTextureSupported === undefined) {
  14985. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14986. if (this._gl.getError() !== 0) {
  14987. this._videoTextureSupported = false;
  14988. }
  14989. else {
  14990. this._videoTextureSupported = true;
  14991. }
  14992. }
  14993. // Copy video through the current working canvas if video texture is not supported
  14994. if (!this._videoTextureSupported) {
  14995. if (!texture._workingCanvas) {
  14996. texture._workingCanvas = document.createElement("canvas");
  14997. var context = texture._workingCanvas.getContext("2d");
  14998. if (!context) {
  14999. throw new Error("Unable to get 2d context");
  15000. }
  15001. texture._workingContext = context;
  15002. texture._workingCanvas.width = texture.width;
  15003. texture._workingCanvas.height = texture.height;
  15004. }
  15005. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15006. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15007. }
  15008. else {
  15009. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15010. }
  15011. if (texture.generateMipMaps) {
  15012. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15013. }
  15014. if (!wasPreviouslyBound) {
  15015. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15016. }
  15017. // this.resetTextureCache();
  15018. texture.isReady = true;
  15019. }
  15020. catch (ex) {
  15021. // Something unexpected
  15022. // Let's disable the texture
  15023. texture._isDisabled = true;
  15024. }
  15025. };
  15026. /**
  15027. * Updates a depth texture Comparison Mode and Function.
  15028. * If the comparison Function is equal to 0, the mode will be set to none.
  15029. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15030. * @param texture The texture to set the comparison function for
  15031. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15032. */
  15033. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15034. if (this.webGLVersion === 1) {
  15035. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15036. return;
  15037. }
  15038. var gl = this._gl;
  15039. if (texture.isCube) {
  15040. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15041. if (comparisonFunction === 0) {
  15042. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15043. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15044. }
  15045. else {
  15046. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15047. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15048. }
  15049. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15050. }
  15051. else {
  15052. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15053. if (comparisonFunction === 0) {
  15054. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15055. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15056. }
  15057. else {
  15058. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15059. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15060. }
  15061. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15062. }
  15063. texture._comparisonFunction = comparisonFunction;
  15064. };
  15065. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15066. var width = size.width || size;
  15067. var height = size.height || size;
  15068. internalTexture.baseWidth = width;
  15069. internalTexture.baseHeight = height;
  15070. internalTexture.width = width;
  15071. internalTexture.height = height;
  15072. internalTexture.isReady = true;
  15073. internalTexture.samples = 1;
  15074. internalTexture.generateMipMaps = false;
  15075. internalTexture._generateDepthBuffer = true;
  15076. internalTexture._generateStencilBuffer = generateStencil;
  15077. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15078. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15079. internalTexture._comparisonFunction = comparisonFunction;
  15080. var gl = this._gl;
  15081. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15082. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15083. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15084. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15085. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15086. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15087. if (comparisonFunction === 0) {
  15088. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15089. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15090. }
  15091. else {
  15092. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15093. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15094. }
  15095. };
  15096. /**
  15097. * Creates a depth stencil texture.
  15098. * This is only available in WebGL 2 or with the depth texture extension available.
  15099. * @param size The size of face edge in the texture.
  15100. * @param options The options defining the texture.
  15101. * @returns The texture
  15102. */
  15103. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15104. if (options.isCube) {
  15105. var width = size.width || size;
  15106. return this._createDepthStencilCubeTexture(width, options);
  15107. }
  15108. else {
  15109. return this._createDepthStencilTexture(size, options);
  15110. }
  15111. };
  15112. /**
  15113. * Creates a depth stencil texture.
  15114. * This is only available in WebGL 2 or with the depth texture extension available.
  15115. * @param size The size of face edge in the texture.
  15116. * @param options The options defining the texture.
  15117. * @returns The texture
  15118. */
  15119. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15120. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15121. if (!this._caps.depthTextureExtension) {
  15122. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15123. return internalTexture;
  15124. }
  15125. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15126. var gl = this._gl;
  15127. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15128. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15129. if (this.webGLVersion > 1) {
  15130. if (internalOptions.generateStencil) {
  15131. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15132. }
  15133. else {
  15134. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15135. }
  15136. }
  15137. else {
  15138. if (internalOptions.generateStencil) {
  15139. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15140. }
  15141. else {
  15142. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15143. }
  15144. }
  15145. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15146. return internalTexture;
  15147. };
  15148. /**
  15149. * Creates a depth stencil cube texture.
  15150. * This is only available in WebGL 2.
  15151. * @param size The size of face edge in the cube texture.
  15152. * @param options The options defining the cube texture.
  15153. * @returns The cube texture
  15154. */
  15155. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15156. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15157. internalTexture.isCube = true;
  15158. if (this.webGLVersion === 1) {
  15159. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15160. return internalTexture;
  15161. }
  15162. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15163. var gl = this._gl;
  15164. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15165. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15166. // Create the depth/stencil buffer
  15167. for (var face = 0; face < 6; face++) {
  15168. if (internalOptions.generateStencil) {
  15169. 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);
  15170. }
  15171. else {
  15172. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15173. }
  15174. }
  15175. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15176. return internalTexture;
  15177. };
  15178. /**
  15179. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15180. * @param renderTarget The render target to set the frame buffer for
  15181. */
  15182. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15183. // Create the framebuffer
  15184. var internalTexture = renderTarget.getInternalTexture();
  15185. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15186. return;
  15187. }
  15188. var gl = this._gl;
  15189. var depthStencilTexture = renderTarget.depthStencilTexture;
  15190. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15191. if (depthStencilTexture.isCube) {
  15192. if (depthStencilTexture._generateStencilBuffer) {
  15193. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15194. }
  15195. else {
  15196. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15197. }
  15198. }
  15199. else {
  15200. if (depthStencilTexture._generateStencilBuffer) {
  15201. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15202. }
  15203. else {
  15204. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15205. }
  15206. }
  15207. this.bindUnboundFramebuffer(null);
  15208. };
  15209. /**
  15210. * Creates a new render target texture
  15211. * @param size defines the size of the texture
  15212. * @param options defines the options used to create the texture
  15213. * @returns a new render target texture stored in an InternalTexture
  15214. */
  15215. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15216. var fullOptions = new RenderTargetCreationOptions();
  15217. if (options !== undefined && typeof options === "object") {
  15218. fullOptions.generateMipMaps = options.generateMipMaps;
  15219. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15220. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15221. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15222. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15223. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15224. }
  15225. else {
  15226. fullOptions.generateMipMaps = options;
  15227. fullOptions.generateDepthBuffer = true;
  15228. fullOptions.generateStencilBuffer = false;
  15229. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15230. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15231. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15232. }
  15233. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15234. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15235. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15236. }
  15237. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15238. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15239. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15240. }
  15241. var gl = this._gl;
  15242. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15243. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15244. var width = size.width || size;
  15245. var height = size.height || size;
  15246. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15247. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15248. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15249. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15250. }
  15251. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15252. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15253. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15254. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15255. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15256. // Create the framebuffer
  15257. var currentFrameBuffer = this._currentFramebuffer;
  15258. var framebuffer = gl.createFramebuffer();
  15259. this.bindUnboundFramebuffer(framebuffer);
  15260. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15261. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15262. if (fullOptions.generateMipMaps) {
  15263. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15264. }
  15265. // Unbind
  15266. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15267. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15268. this.bindUnboundFramebuffer(currentFrameBuffer);
  15269. texture._framebuffer = framebuffer;
  15270. texture.baseWidth = width;
  15271. texture.baseHeight = height;
  15272. texture.width = width;
  15273. texture.height = height;
  15274. texture.isReady = true;
  15275. texture.samples = 1;
  15276. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15277. texture.samplingMode = fullOptions.samplingMode;
  15278. texture.type = fullOptions.type;
  15279. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15280. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15281. // this.resetTextureCache();
  15282. this._internalTexturesCache.push(texture);
  15283. return texture;
  15284. };
  15285. /**
  15286. * Create a multi render target texture
  15287. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15288. * @param size defines the size of the texture
  15289. * @param options defines the creation options
  15290. * @returns the cube texture as an InternalTexture
  15291. */
  15292. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15293. var generateMipMaps = false;
  15294. var generateDepthBuffer = true;
  15295. var generateStencilBuffer = false;
  15296. var generateDepthTexture = false;
  15297. var textureCount = 1;
  15298. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15299. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15300. var types = new Array();
  15301. var samplingModes = new Array();
  15302. if (options !== undefined) {
  15303. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15304. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15305. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15306. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15307. textureCount = options.textureCount || 1;
  15308. if (options.types) {
  15309. types = options.types;
  15310. }
  15311. if (options.samplingModes) {
  15312. samplingModes = options.samplingModes;
  15313. }
  15314. }
  15315. var gl = this._gl;
  15316. // Create the framebuffer
  15317. var framebuffer = gl.createFramebuffer();
  15318. this.bindUnboundFramebuffer(framebuffer);
  15319. var width = size.width || size;
  15320. var height = size.height || size;
  15321. var textures = [];
  15322. var attachments = [];
  15323. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15324. for (var i = 0; i < textureCount; i++) {
  15325. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15326. var type = types[i] || defaultType;
  15327. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15328. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15329. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15330. }
  15331. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15332. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15333. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15334. }
  15335. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15336. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15337. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15338. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15339. }
  15340. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15341. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15342. textures.push(texture);
  15343. attachments.push(attachment);
  15344. gl.activeTexture(gl["TEXTURE" + i]);
  15345. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15346. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15347. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15348. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15349. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15350. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15351. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15352. if (generateMipMaps) {
  15353. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15354. }
  15355. // Unbind
  15356. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15357. texture._framebuffer = framebuffer;
  15358. texture._depthStencilBuffer = depthStencilBuffer;
  15359. texture.baseWidth = width;
  15360. texture.baseHeight = height;
  15361. texture.width = width;
  15362. texture.height = height;
  15363. texture.isReady = true;
  15364. texture.samples = 1;
  15365. texture.generateMipMaps = generateMipMaps;
  15366. texture.samplingMode = samplingMode;
  15367. texture.type = type;
  15368. texture._generateDepthBuffer = generateDepthBuffer;
  15369. texture._generateStencilBuffer = generateStencilBuffer;
  15370. texture._attachments = attachments;
  15371. this._internalTexturesCache.push(texture);
  15372. }
  15373. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15374. // Depth texture
  15375. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15376. gl.activeTexture(gl.TEXTURE0);
  15377. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15378. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15379. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15380. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15381. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15382. 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);
  15383. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15384. depthTexture._framebuffer = framebuffer;
  15385. depthTexture.baseWidth = width;
  15386. depthTexture.baseHeight = height;
  15387. depthTexture.width = width;
  15388. depthTexture.height = height;
  15389. depthTexture.isReady = true;
  15390. depthTexture.samples = 1;
  15391. depthTexture.generateMipMaps = generateMipMaps;
  15392. depthTexture.samplingMode = gl.NEAREST;
  15393. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15394. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15395. textures.push(depthTexture);
  15396. this._internalTexturesCache.push(depthTexture);
  15397. }
  15398. gl.drawBuffers(attachments);
  15399. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15400. this.bindUnboundFramebuffer(null);
  15401. this.resetTextureCache();
  15402. return textures;
  15403. };
  15404. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15405. if (samples === void 0) { samples = 1; }
  15406. var depthStencilBuffer = null;
  15407. var gl = this._gl;
  15408. // Create the depth/stencil buffer
  15409. if (generateStencilBuffer) {
  15410. depthStencilBuffer = gl.createRenderbuffer();
  15411. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15412. if (samples > 1) {
  15413. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15414. }
  15415. else {
  15416. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15417. }
  15418. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15419. }
  15420. else if (generateDepthBuffer) {
  15421. depthStencilBuffer = gl.createRenderbuffer();
  15422. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15423. if (samples > 1) {
  15424. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15425. }
  15426. else {
  15427. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15428. }
  15429. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15430. }
  15431. return depthStencilBuffer;
  15432. };
  15433. /**
  15434. * Updates the sample count of a render target texture
  15435. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15436. * @param texture defines the texture to update
  15437. * @param samples defines the sample count to set
  15438. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15439. */
  15440. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15441. if (this.webGLVersion < 2 || !texture) {
  15442. return 1;
  15443. }
  15444. if (texture.samples === samples) {
  15445. return samples;
  15446. }
  15447. var gl = this._gl;
  15448. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15449. // Dispose previous render buffers
  15450. if (texture._depthStencilBuffer) {
  15451. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15452. texture._depthStencilBuffer = null;
  15453. }
  15454. if (texture._MSAAFramebuffer) {
  15455. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15456. texture._MSAAFramebuffer = null;
  15457. }
  15458. if (texture._MSAARenderBuffer) {
  15459. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15460. texture._MSAARenderBuffer = null;
  15461. }
  15462. if (samples > 1) {
  15463. var framebuffer = gl.createFramebuffer();
  15464. if (!framebuffer) {
  15465. throw new Error("Unable to create multi sampled framebuffer");
  15466. }
  15467. texture._MSAAFramebuffer = framebuffer;
  15468. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15469. var colorRenderbuffer = gl.createRenderbuffer();
  15470. if (!colorRenderbuffer) {
  15471. throw new Error("Unable to create multi sampled framebuffer");
  15472. }
  15473. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15474. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15475. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15476. texture._MSAARenderBuffer = colorRenderbuffer;
  15477. }
  15478. else {
  15479. this.bindUnboundFramebuffer(texture._framebuffer);
  15480. }
  15481. texture.samples = samples;
  15482. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15483. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15484. this.bindUnboundFramebuffer(null);
  15485. return samples;
  15486. };
  15487. /**
  15488. * Update the sample count for a given multiple render target texture
  15489. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15490. * @param textures defines the textures to update
  15491. * @param samples defines the sample count to set
  15492. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15493. */
  15494. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15495. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15496. return 1;
  15497. }
  15498. if (textures[0].samples === samples) {
  15499. return samples;
  15500. }
  15501. var gl = this._gl;
  15502. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15503. // Dispose previous render buffers
  15504. if (textures[0]._depthStencilBuffer) {
  15505. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15506. textures[0]._depthStencilBuffer = null;
  15507. }
  15508. if (textures[0]._MSAAFramebuffer) {
  15509. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15510. textures[0]._MSAAFramebuffer = null;
  15511. }
  15512. for (var i = 0; i < textures.length; i++) {
  15513. if (textures[i]._MSAARenderBuffer) {
  15514. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15515. textures[i]._MSAARenderBuffer = null;
  15516. }
  15517. }
  15518. if (samples > 1) {
  15519. var framebuffer = gl.createFramebuffer();
  15520. if (!framebuffer) {
  15521. throw new Error("Unable to create multi sampled framebuffer");
  15522. }
  15523. this.bindUnboundFramebuffer(framebuffer);
  15524. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15525. var attachments = [];
  15526. for (var i = 0; i < textures.length; i++) {
  15527. var texture = textures[i];
  15528. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15529. var colorRenderbuffer = gl.createRenderbuffer();
  15530. if (!colorRenderbuffer) {
  15531. throw new Error("Unable to create multi sampled framebuffer");
  15532. }
  15533. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15534. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15535. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15536. texture._MSAAFramebuffer = framebuffer;
  15537. texture._MSAARenderBuffer = colorRenderbuffer;
  15538. texture.samples = samples;
  15539. texture._depthStencilBuffer = depthStencilBuffer;
  15540. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15541. attachments.push(attachment);
  15542. }
  15543. gl.drawBuffers(attachments);
  15544. }
  15545. else {
  15546. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15547. }
  15548. this.bindUnboundFramebuffer(null);
  15549. return samples;
  15550. };
  15551. /** @hidden */
  15552. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15553. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15554. };
  15555. /** @hidden */
  15556. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15557. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15558. };
  15559. /** @hidden */
  15560. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15561. var gl = this._gl;
  15562. var textureType = this._getWebGLTextureType(texture.type);
  15563. var format = this._getInternalFormat(texture.format);
  15564. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15565. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15566. this._bindTextureDirectly(bindTarget, texture, true);
  15567. this._unpackFlipY(texture.invertY);
  15568. var target = gl.TEXTURE_2D;
  15569. if (texture.isCube) {
  15570. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15571. }
  15572. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15573. this._bindTextureDirectly(bindTarget, null, true);
  15574. };
  15575. /**
  15576. * Creates a new render target cube texture
  15577. * @param size defines the size of the texture
  15578. * @param options defines the options used to create the texture
  15579. * @returns a new render target cube texture stored in an InternalTexture
  15580. */
  15581. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15582. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15583. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15584. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15585. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15586. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15587. }
  15588. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15589. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15590. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15591. }
  15592. var gl = this._gl;
  15593. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15594. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15595. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15596. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15597. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15598. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15599. }
  15600. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15601. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15602. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15603. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15604. for (var face = 0; face < 6; face++) {
  15605. 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);
  15606. }
  15607. // Create the framebuffer
  15608. var framebuffer = gl.createFramebuffer();
  15609. this.bindUnboundFramebuffer(framebuffer);
  15610. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15611. // MipMaps
  15612. if (fullOptions.generateMipMaps) {
  15613. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15614. }
  15615. // Unbind
  15616. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15617. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15618. this.bindUnboundFramebuffer(null);
  15619. texture._framebuffer = framebuffer;
  15620. texture.width = size;
  15621. texture.height = size;
  15622. texture.isReady = true;
  15623. texture.isCube = true;
  15624. texture.samples = 1;
  15625. texture.generateMipMaps = fullOptions.generateMipMaps;
  15626. texture.samplingMode = fullOptions.samplingMode;
  15627. texture.type = fullOptions.type;
  15628. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15629. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15630. this._internalTexturesCache.push(texture);
  15631. return texture;
  15632. };
  15633. /**
  15634. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15635. * @param rootUrl defines the url where the file to load is located
  15636. * @param scene defines the current scene
  15637. * @param lodScale defines scale to apply to the mip map selection
  15638. * @param lodOffset defines offset to apply to the mip map selection
  15639. * @param onLoad defines an optional callback raised when the texture is loaded
  15640. * @param onError defines an optional callback raised if there is an issue to load the texture
  15641. * @param format defines the format of the data
  15642. * @param forcedExtension defines the extension to use to pick the right loader
  15643. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15644. * @returns the cube texture as an InternalTexture
  15645. */
  15646. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15647. var _this = this;
  15648. if (onLoad === void 0) { onLoad = null; }
  15649. if (onError === void 0) { onError = null; }
  15650. if (forcedExtension === void 0) { forcedExtension = null; }
  15651. if (createPolynomials === void 0) { createPolynomials = true; }
  15652. var callback = function (loadData) {
  15653. if (!loadData) {
  15654. if (onLoad) {
  15655. onLoad(null);
  15656. }
  15657. return;
  15658. }
  15659. var texture = loadData.texture;
  15660. if (!createPolynomials) {
  15661. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15662. }
  15663. else if (loadData.info.sphericalPolynomial) {
  15664. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15665. }
  15666. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15667. if (_this._caps.textureLOD) {
  15668. // Do not add extra process if texture lod is supported.
  15669. if (onLoad) {
  15670. onLoad(texture);
  15671. }
  15672. return;
  15673. }
  15674. var mipSlices = 3;
  15675. var gl = _this._gl;
  15676. var width = loadData.width;
  15677. if (!width) {
  15678. return;
  15679. }
  15680. var textures = [];
  15681. for (var i = 0; i < mipSlices; i++) {
  15682. //compute LOD from even spacing in smoothness (matching shader calculation)
  15683. var smoothness = i / (mipSlices - 1);
  15684. var roughness = 1 - smoothness;
  15685. var minLODIndex = lodOffset; // roughness = 0
  15686. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15687. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15688. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15689. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15690. glTextureFromLod.isCube = true;
  15691. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15692. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15693. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15694. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15695. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15696. if (loadData.isDDS) {
  15697. var info = loadData.info;
  15698. var data = loadData.data;
  15699. _this._unpackFlipY(info.isCompressed);
  15700. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15701. }
  15702. else {
  15703. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15704. }
  15705. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15706. // Wrap in a base texture for easy binding.
  15707. var lodTexture = new BABYLON.BaseTexture(scene);
  15708. lodTexture.isCube = true;
  15709. lodTexture._texture = glTextureFromLod;
  15710. glTextureFromLod.isReady = true;
  15711. textures.push(lodTexture);
  15712. }
  15713. texture._lodTextureHigh = textures[2];
  15714. texture._lodTextureMid = textures[1];
  15715. texture._lodTextureLow = textures[0];
  15716. if (onLoad) {
  15717. onLoad(texture);
  15718. }
  15719. };
  15720. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15721. };
  15722. /**
  15723. * Creates a cube texture
  15724. * @param rootUrl defines the url where the files to load is located
  15725. * @param scene defines the current scene
  15726. * @param files defines the list of files to load (1 per face)
  15727. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15728. * @param onLoad defines an optional callback raised when the texture is loaded
  15729. * @param onError defines an optional callback raised if there is an issue to load the texture
  15730. * @param format defines the format of the data
  15731. * @param forcedExtension defines the extension to use to pick the right loader
  15732. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15733. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15734. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15735. * @returns the cube texture as an InternalTexture
  15736. */
  15737. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset) {
  15738. var _this = this;
  15739. if (onLoad === void 0) { onLoad = null; }
  15740. if (onError === void 0) { onError = null; }
  15741. if (forcedExtension === void 0) { forcedExtension = null; }
  15742. if (createPolynomials === void 0) { createPolynomials = false; }
  15743. if (lodScale === void 0) { lodScale = 0; }
  15744. if (lodOffset === void 0) { lodOffset = 0; }
  15745. var gl = this._gl;
  15746. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15747. texture.isCube = true;
  15748. texture.url = rootUrl;
  15749. texture.generateMipMaps = !noMipmap;
  15750. texture._lodGenerationScale = lodScale;
  15751. texture._lodGenerationOffset = lodOffset;
  15752. if (!this._doNotHandleContextLost) {
  15753. texture._extension = forcedExtension;
  15754. texture._files = files;
  15755. }
  15756. var isKTX = false;
  15757. var isDDS = false;
  15758. var isEnv = false;
  15759. var lastDot = rootUrl.lastIndexOf('.');
  15760. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15761. if (this._textureFormatInUse) {
  15762. extension = this._textureFormatInUse;
  15763. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15764. isKTX = true;
  15765. }
  15766. else {
  15767. isDDS = (extension === ".dds");
  15768. isEnv = (extension === ".env");
  15769. }
  15770. var onerror = function (request, exception) {
  15771. if (onError && request) {
  15772. onError(request.status + " " + request.statusText, exception);
  15773. }
  15774. };
  15775. if (isKTX) {
  15776. this._loadFile(rootUrl, function (data) {
  15777. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15778. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15779. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15780. _this._unpackFlipY(true);
  15781. ktx.uploadLevels(_this._gl, !noMipmap);
  15782. _this.setCubeMapTextureParams(gl, loadMipmap);
  15783. texture.width = ktx.pixelWidth;
  15784. texture.height = ktx.pixelHeight;
  15785. texture.isReady = true;
  15786. }, undefined, undefined, true, onerror);
  15787. }
  15788. else if (isEnv) {
  15789. this._loadFile(rootUrl, function (data) {
  15790. data = data;
  15791. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15792. if (info) {
  15793. texture.width = info.width;
  15794. texture.height = info.width;
  15795. BABYLON.EnvironmentTextureTools.UploadPolynomials(texture, data, info);
  15796. BABYLON.EnvironmentTextureTools.UploadLevelsAsync(texture, data, info).then(function () {
  15797. texture.isReady = true;
  15798. if (onLoad) {
  15799. onLoad();
  15800. }
  15801. });
  15802. }
  15803. else if (onError) {
  15804. onError("Can not parse the environment file", null);
  15805. }
  15806. }, undefined, undefined, true, onerror);
  15807. }
  15808. else if (isDDS) {
  15809. if (files && files.length === 6) {
  15810. this._cascadeLoadFiles(scene, function (imgs) {
  15811. var info;
  15812. var loadMipmap = false;
  15813. var width = 0;
  15814. for (var index = 0; index < imgs.length; index++) {
  15815. var data = imgs[index];
  15816. info = BABYLON.DDSTools.GetDDSInfo(data);
  15817. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15818. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15819. _this._unpackFlipY(info.isCompressed);
  15820. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15821. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15822. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15823. }
  15824. texture.width = info.width;
  15825. texture.height = info.height;
  15826. texture.type = info.textureType;
  15827. width = info.width;
  15828. }
  15829. _this.setCubeMapTextureParams(gl, loadMipmap);
  15830. texture.isReady = true;
  15831. if (onLoad) {
  15832. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15833. }
  15834. }, files, onError);
  15835. }
  15836. else {
  15837. this._loadFile(rootUrl, function (data) {
  15838. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15839. if (createPolynomials) {
  15840. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15841. }
  15842. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15843. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15844. _this._unpackFlipY(info.isCompressed);
  15845. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15846. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15847. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15848. }
  15849. _this.setCubeMapTextureParams(gl, loadMipmap);
  15850. texture.width = info.width;
  15851. texture.height = info.height;
  15852. texture.isReady = true;
  15853. texture.type = info.textureType;
  15854. if (onLoad) {
  15855. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15856. }
  15857. }, undefined, undefined, true, onerror);
  15858. }
  15859. }
  15860. else {
  15861. if (!files) {
  15862. throw new Error("Cannot load cubemap because files were not defined");
  15863. }
  15864. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15865. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15866. var height = width;
  15867. _this._prepareWorkingCanvas();
  15868. if (!_this._workingCanvas || !_this._workingContext) {
  15869. return;
  15870. }
  15871. _this._workingCanvas.width = width;
  15872. _this._workingCanvas.height = height;
  15873. var faces = [
  15874. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15875. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15876. ];
  15877. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15878. _this._unpackFlipY(false);
  15879. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15880. for (var index = 0; index < faces.length; index++) {
  15881. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15882. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15883. }
  15884. if (!noMipmap) {
  15885. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15886. }
  15887. _this.setCubeMapTextureParams(gl, !noMipmap);
  15888. texture.width = width;
  15889. texture.height = height;
  15890. texture.isReady = true;
  15891. if (format) {
  15892. texture.format = format;
  15893. }
  15894. texture.onLoadedObservable.notifyObservers(texture);
  15895. texture.onLoadedObservable.clear();
  15896. if (onLoad) {
  15897. onLoad();
  15898. }
  15899. }, files, onError);
  15900. }
  15901. this._internalTexturesCache.push(texture);
  15902. return texture;
  15903. };
  15904. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15905. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15906. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15907. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15908. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15909. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15910. // this.resetTextureCache();
  15911. };
  15912. /**
  15913. * Update a raw cube texture
  15914. * @param texture defines the texture to udpdate
  15915. * @param data defines the data to store
  15916. * @param format defines the data format
  15917. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15918. * @param invertY defines if data must be stored with Y axis inverted
  15919. * @param compression defines the compression used (null by default)
  15920. * @param level defines which level of the texture to update
  15921. */
  15922. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15923. if (compression === void 0) { compression = null; }
  15924. if (level === void 0) { level = 0; }
  15925. texture._bufferViewArray = data;
  15926. texture.format = format;
  15927. texture.type = type;
  15928. texture.invertY = invertY;
  15929. texture._compression = compression;
  15930. var gl = this._gl;
  15931. var textureType = this._getWebGLTextureType(type);
  15932. var internalFormat = this._getInternalFormat(format);
  15933. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15934. var needConversion = false;
  15935. if (internalFormat === gl.RGB) {
  15936. internalFormat = gl.RGBA;
  15937. needConversion = true;
  15938. }
  15939. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15940. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15941. if (texture.width % 4 !== 0) {
  15942. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15943. }
  15944. // Data are known to be in +X +Y +Z -X -Y -Z
  15945. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15946. var faceData = data[faceIndex];
  15947. if (compression) {
  15948. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15949. }
  15950. else {
  15951. if (needConversion) {
  15952. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15953. }
  15954. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15955. }
  15956. }
  15957. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15958. if (isPot && texture.generateMipMaps && level === 0) {
  15959. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15960. }
  15961. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15962. // this.resetTextureCache();
  15963. texture.isReady = true;
  15964. };
  15965. /**
  15966. * Creates a new raw cube texture
  15967. * @param data defines the array of data to use to create each face
  15968. * @param size defines the size of the textures
  15969. * @param format defines the format of the data
  15970. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15971. * @param generateMipMaps defines if the engine should generate the mip levels
  15972. * @param invertY defines if data must be stored with Y axis inverted
  15973. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15974. * @param compression defines the compression used (null by default)
  15975. * @returns the cube texture as an InternalTexture
  15976. */
  15977. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15978. if (compression === void 0) { compression = null; }
  15979. var gl = this._gl;
  15980. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15981. texture.isCube = true;
  15982. texture.generateMipMaps = generateMipMaps;
  15983. texture.format = format;
  15984. texture.type = type;
  15985. if (!this._doNotHandleContextLost) {
  15986. texture._bufferViewArray = data;
  15987. }
  15988. var textureType = this._getWebGLTextureType(type);
  15989. var internalFormat = this._getInternalFormat(format);
  15990. if (internalFormat === gl.RGB) {
  15991. internalFormat = gl.RGBA;
  15992. }
  15993. var width = size;
  15994. var height = width;
  15995. texture.width = width;
  15996. texture.height = height;
  15997. // Double check on POT to generate Mips.
  15998. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15999. if (!isPot) {
  16000. generateMipMaps = false;
  16001. }
  16002. // Upload data if needed. The texture won't be ready until then.
  16003. if (data) {
  16004. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16005. }
  16006. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16007. // Filters
  16008. if (data && generateMipMaps) {
  16009. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16010. }
  16011. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16012. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16013. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16014. }
  16015. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16016. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16017. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16018. }
  16019. else {
  16020. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  16021. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16022. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16023. }
  16024. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16025. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16026. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16027. return texture;
  16028. };
  16029. /**
  16030. * Creates a new raw cube texture from a specified url
  16031. * @param url defines the url where the data is located
  16032. * @param scene defines the current scene
  16033. * @param size defines the size of the textures
  16034. * @param format defines the format of the data
  16035. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16036. * @param noMipmap defines if the engine should avoid generating the mip levels
  16037. * @param callback defines a callback used to extract texture data from loaded data
  16038. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16039. * @param onLoad defines a callback called when texture is loaded
  16040. * @param onError defines a callback called if there is an error
  16041. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16042. * @param invertY defines if data must be stored with Y axis inverted
  16043. * @returns the cube texture as an InternalTexture
  16044. */
  16045. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16046. var _this = this;
  16047. if (onLoad === void 0) { onLoad = null; }
  16048. if (onError === void 0) { onError = null; }
  16049. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16050. if (invertY === void 0) { invertY = false; }
  16051. var gl = this._gl;
  16052. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16053. scene._addPendingData(texture);
  16054. texture.url = url;
  16055. this._internalTexturesCache.push(texture);
  16056. var onerror = function (request, exception) {
  16057. scene._removePendingData(texture);
  16058. if (onError && request) {
  16059. onError(request.status + " " + request.statusText, exception);
  16060. }
  16061. };
  16062. var internalCallback = function (data) {
  16063. var width = texture.width;
  16064. var faceDataArrays = callback(data);
  16065. if (!faceDataArrays) {
  16066. return;
  16067. }
  16068. if (mipmapGenerator) {
  16069. var textureType = _this._getWebGLTextureType(type);
  16070. var internalFormat = _this._getInternalFormat(format);
  16071. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16072. var needConversion = false;
  16073. if (internalFormat === gl.RGB) {
  16074. internalFormat = gl.RGBA;
  16075. needConversion = true;
  16076. }
  16077. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16078. _this._unpackFlipY(false);
  16079. var mipData = mipmapGenerator(faceDataArrays);
  16080. for (var level = 0; level < mipData.length; level++) {
  16081. var mipSize = width >> level;
  16082. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16083. var mipFaceData = mipData[level][faceIndex];
  16084. if (needConversion) {
  16085. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16086. }
  16087. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16088. }
  16089. }
  16090. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16091. }
  16092. else {
  16093. texture.generateMipMaps = !noMipmap;
  16094. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16095. }
  16096. texture.isReady = true;
  16097. // this.resetTextureCache();
  16098. scene._removePendingData(texture);
  16099. if (onLoad) {
  16100. onLoad();
  16101. }
  16102. };
  16103. this._loadFile(url, function (data) {
  16104. internalCallback(data);
  16105. }, undefined, scene.database, true, onerror);
  16106. return texture;
  16107. };
  16108. ;
  16109. /**
  16110. * Update a raw 3D texture
  16111. * @param texture defines the texture to update
  16112. * @param data defines the data to store
  16113. * @param format defines the data format
  16114. * @param invertY defines if data must be stored with Y axis inverted
  16115. * @param compression defines the used compression (can be null)
  16116. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16117. */
  16118. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16119. if (compression === void 0) { compression = null; }
  16120. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16121. var internalType = this._getWebGLTextureType(textureType);
  16122. var internalFormat = this._getInternalFormat(format);
  16123. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16124. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16125. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16126. if (!this._doNotHandleContextLost) {
  16127. texture._bufferView = data;
  16128. texture.format = format;
  16129. texture.invertY = invertY;
  16130. texture._compression = compression;
  16131. }
  16132. if (texture.width % 4 !== 0) {
  16133. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16134. }
  16135. if (compression && data) {
  16136. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16137. }
  16138. else {
  16139. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16140. }
  16141. if (texture.generateMipMaps) {
  16142. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16143. }
  16144. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16145. // this.resetTextureCache();
  16146. texture.isReady = true;
  16147. };
  16148. /**
  16149. * Creates a new raw 3D texture
  16150. * @param data defines the data used to create the texture
  16151. * @param width defines the width of the texture
  16152. * @param height defines the height of the texture
  16153. * @param depth defines the depth of the texture
  16154. * @param format defines the format of the texture
  16155. * @param generateMipMaps defines if the engine must generate mip levels
  16156. * @param invertY defines if data must be stored with Y axis inverted
  16157. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16158. * @param compression defines the compressed used (can be null)
  16159. * @param textureType defines the compressed used (can be null)
  16160. * @returns a new raw 3D texture (stored in an InternalTexture)
  16161. */
  16162. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16163. if (compression === void 0) { compression = null; }
  16164. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16165. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16166. texture.baseWidth = width;
  16167. texture.baseHeight = height;
  16168. texture.baseDepth = depth;
  16169. texture.width = width;
  16170. texture.height = height;
  16171. texture.depth = depth;
  16172. texture.format = format;
  16173. texture.type = textureType;
  16174. texture.generateMipMaps = generateMipMaps;
  16175. texture.samplingMode = samplingMode;
  16176. texture.is3D = true;
  16177. if (!this._doNotHandleContextLost) {
  16178. texture._bufferView = data;
  16179. }
  16180. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16181. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16182. // Filters
  16183. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16184. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16185. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16186. if (generateMipMaps) {
  16187. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16188. }
  16189. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16190. this._internalTexturesCache.push(texture);
  16191. return texture;
  16192. };
  16193. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16194. var gl = this._gl;
  16195. if (!gl) {
  16196. return;
  16197. }
  16198. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16199. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16200. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16201. if (!noMipmap && !isCompressed) {
  16202. gl.generateMipmap(gl.TEXTURE_2D);
  16203. }
  16204. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16205. // this.resetTextureCache();
  16206. if (scene) {
  16207. scene._removePendingData(texture);
  16208. }
  16209. texture.onLoadedObservable.notifyObservers(texture);
  16210. texture.onLoadedObservable.clear();
  16211. };
  16212. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16213. var _this = this;
  16214. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16215. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16216. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16217. var gl = this._gl;
  16218. if (!gl) {
  16219. return;
  16220. }
  16221. if (!texture._webGLTexture) {
  16222. // this.resetTextureCache();
  16223. if (scene) {
  16224. scene._removePendingData(texture);
  16225. }
  16226. return;
  16227. }
  16228. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16229. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16230. texture.baseWidth = width;
  16231. texture.baseHeight = height;
  16232. texture.width = potWidth;
  16233. texture.height = potHeight;
  16234. texture.isReady = true;
  16235. if (processFunction(potWidth, potHeight, function () {
  16236. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16237. })) {
  16238. // Returning as texture needs extra async steps
  16239. return;
  16240. }
  16241. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16242. };
  16243. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16244. // Create new RGBA data container.
  16245. var rgbaData;
  16246. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16247. rgbaData = new Float32Array(width * height * 4);
  16248. }
  16249. else {
  16250. rgbaData = new Uint32Array(width * height * 4);
  16251. }
  16252. // Convert each pixel.
  16253. for (var x = 0; x < width; x++) {
  16254. for (var y = 0; y < height; y++) {
  16255. var index = (y * width + x) * 3;
  16256. var newIndex = (y * width + x) * 4;
  16257. // Map Old Value to new value.
  16258. rgbaData[newIndex + 0] = rgbData[index + 0];
  16259. rgbaData[newIndex + 1] = rgbData[index + 1];
  16260. rgbaData[newIndex + 2] = rgbData[index + 2];
  16261. // Add fully opaque alpha channel.
  16262. rgbaData[newIndex + 3] = 1;
  16263. }
  16264. }
  16265. return rgbaData;
  16266. };
  16267. /** @hidden */
  16268. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16269. var gl = this._gl;
  16270. if (texture._framebuffer) {
  16271. gl.deleteFramebuffer(texture._framebuffer);
  16272. texture._framebuffer = null;
  16273. }
  16274. if (texture._depthStencilBuffer) {
  16275. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16276. texture._depthStencilBuffer = null;
  16277. }
  16278. if (texture._MSAAFramebuffer) {
  16279. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16280. texture._MSAAFramebuffer = null;
  16281. }
  16282. if (texture._MSAARenderBuffer) {
  16283. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16284. texture._MSAARenderBuffer = null;
  16285. }
  16286. };
  16287. /** @hidden */
  16288. Engine.prototype._releaseTexture = function (texture) {
  16289. var gl = this._gl;
  16290. this._releaseFramebufferObjects(texture);
  16291. gl.deleteTexture(texture._webGLTexture);
  16292. // Unbind channels
  16293. this.unbindAllTextures();
  16294. var index = this._internalTexturesCache.indexOf(texture);
  16295. if (index !== -1) {
  16296. this._internalTexturesCache.splice(index, 1);
  16297. }
  16298. // Integrated fixed lod samplers.
  16299. if (texture._lodTextureHigh) {
  16300. texture._lodTextureHigh.dispose();
  16301. }
  16302. if (texture._lodTextureMid) {
  16303. texture._lodTextureMid.dispose();
  16304. }
  16305. if (texture._lodTextureLow) {
  16306. texture._lodTextureLow.dispose();
  16307. }
  16308. // Set output texture of post process to null if the texture has been released/disposed
  16309. this.scenes.forEach(function (scene) {
  16310. scene.postProcesses.forEach(function (postProcess) {
  16311. if (postProcess._outputTexture == texture) {
  16312. postProcess._outputTexture = null;
  16313. }
  16314. });
  16315. scene.cameras.forEach(function (camera) {
  16316. camera._postProcesses.forEach(function (postProcess) {
  16317. if (postProcess) {
  16318. if (postProcess._outputTexture == texture) {
  16319. postProcess._outputTexture = null;
  16320. }
  16321. }
  16322. });
  16323. });
  16324. });
  16325. };
  16326. Engine.prototype.setProgram = function (program) {
  16327. if (this._currentProgram !== program) {
  16328. this._gl.useProgram(program);
  16329. this._currentProgram = program;
  16330. }
  16331. };
  16332. /**
  16333. * Binds an effect to the webGL context
  16334. * @param effect defines the effect to bind
  16335. */
  16336. Engine.prototype.bindSamplers = function (effect) {
  16337. this.setProgram(effect.getProgram());
  16338. var samplers = effect.getSamplers();
  16339. for (var index = 0; index < samplers.length; index++) {
  16340. var uniform = effect.getUniform(samplers[index]);
  16341. if (uniform) {
  16342. this._boundUniforms[index] = uniform;
  16343. }
  16344. }
  16345. this._currentEffect = null;
  16346. };
  16347. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16348. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16349. return;
  16350. }
  16351. // Remove
  16352. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16353. // Bind last to it
  16354. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16355. // Bind to dummy
  16356. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16357. };
  16358. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16359. if (!internalTexture) {
  16360. return -1;
  16361. }
  16362. internalTexture._initialSlot = channel;
  16363. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16364. if (channel !== internalTexture._designatedSlot) {
  16365. this._textureCollisions.addCount(1, false);
  16366. }
  16367. }
  16368. else {
  16369. if (channel !== internalTexture._designatedSlot) {
  16370. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16371. return internalTexture._designatedSlot;
  16372. }
  16373. else {
  16374. // No slot for this texture, let's pick a new one (if we find a free slot)
  16375. if (this._nextFreeTextureSlots.length) {
  16376. return this._nextFreeTextureSlots[0];
  16377. }
  16378. // We need to recycle the oldest bound texture, sorry.
  16379. this._textureCollisions.addCount(1, false);
  16380. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16381. }
  16382. }
  16383. }
  16384. return channel;
  16385. };
  16386. Engine.prototype._linkTrackers = function (previous, next) {
  16387. previous.next = next;
  16388. next.previous = previous;
  16389. };
  16390. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16391. var currentSlot = internalTexture._designatedSlot;
  16392. if (currentSlot === -1) {
  16393. return -1;
  16394. }
  16395. internalTexture._designatedSlot = -1;
  16396. if (this.disableTextureBindingOptimization) {
  16397. return -1;
  16398. }
  16399. // Remove from bound list
  16400. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16401. // Free the slot
  16402. this._boundTexturesCache[currentSlot] = null;
  16403. this._nextFreeTextureSlots.push(currentSlot);
  16404. return currentSlot;
  16405. };
  16406. Engine.prototype._activateCurrentTexture = function () {
  16407. if (this._currentTextureChannel !== this._activeChannel) {
  16408. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16409. this._currentTextureChannel = this._activeChannel;
  16410. }
  16411. };
  16412. /** @hidden */
  16413. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16414. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16415. if (force === void 0) { force = false; }
  16416. var wasPreviouslyBound = false;
  16417. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16418. this._activeChannel = texture._designatedSlot;
  16419. }
  16420. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16421. var isTextureForRendering = texture && texture._initialSlot > -1;
  16422. if (currentTextureBound !== texture || force) {
  16423. if (currentTextureBound) {
  16424. this._removeDesignatedSlot(currentTextureBound);
  16425. }
  16426. this._activateCurrentTexture();
  16427. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16428. this._boundTexturesCache[this._activeChannel] = texture;
  16429. if (texture) {
  16430. if (!this.disableTextureBindingOptimization) {
  16431. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16432. if (slotIndex > -1) {
  16433. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16434. }
  16435. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16436. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16437. }
  16438. texture._designatedSlot = this._activeChannel;
  16439. }
  16440. }
  16441. else if (forTextureDataUpdate) {
  16442. wasPreviouslyBound = true;
  16443. this._activateCurrentTexture();
  16444. }
  16445. if (isTextureForRendering && !forTextureDataUpdate) {
  16446. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16447. }
  16448. return wasPreviouslyBound;
  16449. };
  16450. /** @hidden */
  16451. Engine.prototype._bindTexture = function (channel, texture) {
  16452. if (channel < 0) {
  16453. return;
  16454. }
  16455. if (texture) {
  16456. channel = this._getCorrectTextureChannel(channel, texture);
  16457. }
  16458. this._activeChannel = channel;
  16459. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16460. };
  16461. /**
  16462. * Sets a texture to the webGL context from a postprocess
  16463. * @param channel defines the channel to use
  16464. * @param postProcess defines the source postprocess
  16465. */
  16466. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16467. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16468. };
  16469. /**
  16470. * Binds the output of the passed in post process to the texture channel specified
  16471. * @param channel The channel the texture should be bound to
  16472. * @param postProcess The post process which's output should be bound
  16473. */
  16474. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16475. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16476. };
  16477. /**
  16478. * Unbind all textures from the webGL context
  16479. */
  16480. Engine.prototype.unbindAllTextures = function () {
  16481. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16482. this._activeChannel = channel;
  16483. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16484. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16485. if (this.webGLVersion > 1) {
  16486. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16487. }
  16488. }
  16489. };
  16490. /**
  16491. * Sets a texture to the according uniform.
  16492. * @param channel The texture channel
  16493. * @param uniform The uniform to set
  16494. * @param texture The texture to apply
  16495. */
  16496. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16497. if (channel < 0) {
  16498. return;
  16499. }
  16500. if (uniform) {
  16501. this._boundUniforms[channel] = uniform;
  16502. }
  16503. this._setTexture(channel, texture);
  16504. };
  16505. /**
  16506. * Sets a depth stencil texture from a render target to the according uniform.
  16507. * @param channel The texture channel
  16508. * @param uniform The uniform to set
  16509. * @param texture The render target texture containing the depth stencil texture to apply
  16510. */
  16511. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16512. if (channel < 0) {
  16513. return;
  16514. }
  16515. if (uniform) {
  16516. this._boundUniforms[channel] = uniform;
  16517. }
  16518. if (!texture || !texture.depthStencilTexture) {
  16519. this._setTexture(channel, null);
  16520. }
  16521. else {
  16522. this._setTexture(channel, texture, false, true);
  16523. }
  16524. };
  16525. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16526. var uniform = this._boundUniforms[sourceSlot];
  16527. if (uniform._currentState === destination) {
  16528. return;
  16529. }
  16530. this._gl.uniform1i(uniform, destination);
  16531. uniform._currentState = destination;
  16532. };
  16533. Engine.prototype._getTextureWrapMode = function (mode) {
  16534. switch (mode) {
  16535. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16536. return this._gl.REPEAT;
  16537. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16538. return this._gl.CLAMP_TO_EDGE;
  16539. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16540. return this._gl.MIRRORED_REPEAT;
  16541. }
  16542. return this._gl.REPEAT;
  16543. };
  16544. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16545. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16546. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16547. // Not ready?
  16548. if (!texture) {
  16549. if (this._boundTexturesCache[channel] != null) {
  16550. this._activeChannel = channel;
  16551. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16552. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16553. if (this.webGLVersion > 1) {
  16554. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16555. }
  16556. }
  16557. return false;
  16558. }
  16559. // Video
  16560. if (texture.video) {
  16561. this._activeChannel = channel;
  16562. texture.update();
  16563. }
  16564. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16565. texture.delayLoad();
  16566. return false;
  16567. }
  16568. var internalTexture;
  16569. if (depthStencilTexture) {
  16570. internalTexture = texture.depthStencilTexture;
  16571. }
  16572. else if (texture.isReady()) {
  16573. internalTexture = texture.getInternalTexture();
  16574. }
  16575. else if (texture.isCube) {
  16576. internalTexture = this.emptyCubeTexture;
  16577. }
  16578. else if (texture.is3D) {
  16579. internalTexture = this.emptyTexture3D;
  16580. }
  16581. else {
  16582. internalTexture = this.emptyTexture;
  16583. }
  16584. if (!isPartOfTextureArray) {
  16585. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16586. }
  16587. var needToBind = true;
  16588. if (this._boundTexturesCache[channel] === internalTexture) {
  16589. this._moveBoundTextureOnTop(internalTexture);
  16590. if (!isPartOfTextureArray) {
  16591. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16592. }
  16593. needToBind = false;
  16594. }
  16595. this._activeChannel = channel;
  16596. if (internalTexture && internalTexture.is3D) {
  16597. if (needToBind) {
  16598. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16599. }
  16600. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16601. internalTexture._cachedWrapU = texture.wrapU;
  16602. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16603. }
  16604. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16605. internalTexture._cachedWrapV = texture.wrapV;
  16606. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16607. }
  16608. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16609. internalTexture._cachedWrapR = texture.wrapR;
  16610. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16611. }
  16612. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16613. }
  16614. else if (internalTexture && internalTexture.isCube) {
  16615. if (needToBind) {
  16616. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16617. }
  16618. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16619. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16620. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16621. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16622. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16623. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16624. }
  16625. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16626. }
  16627. else {
  16628. if (needToBind) {
  16629. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16630. }
  16631. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16632. internalTexture._cachedWrapU = texture.wrapU;
  16633. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16634. }
  16635. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16636. internalTexture._cachedWrapV = texture.wrapV;
  16637. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16638. }
  16639. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16640. }
  16641. return true;
  16642. };
  16643. /**
  16644. * Sets an array of texture to the webGL context
  16645. * @param channel defines the channel where the texture array must be set
  16646. * @param uniform defines the associated uniform location
  16647. * @param textures defines the array of textures to bind
  16648. */
  16649. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16650. if (channel < 0 || !uniform) {
  16651. return;
  16652. }
  16653. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16654. this._textureUnits = new Int32Array(textures.length);
  16655. }
  16656. for (var i = 0; i < textures.length; i++) {
  16657. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16658. }
  16659. this._gl.uniform1iv(uniform, this._textureUnits);
  16660. for (var index = 0; index < textures.length; index++) {
  16661. this._setTexture(this._textureUnits[index], textures[index], true);
  16662. }
  16663. };
  16664. /** @hidden */
  16665. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16666. var internalTexture = texture.getInternalTexture();
  16667. if (!internalTexture) {
  16668. return;
  16669. }
  16670. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16671. var value = texture.anisotropicFilteringLevel;
  16672. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16673. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16674. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16675. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16676. }
  16677. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16678. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16679. internalTexture._cachedAnisotropicFilteringLevel = value;
  16680. }
  16681. };
  16682. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16683. this._bindTextureDirectly(target, texture, true, true);
  16684. this._gl.texParameterf(target, parameter, value);
  16685. };
  16686. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16687. if (texture) {
  16688. this._bindTextureDirectly(target, texture, true, true);
  16689. }
  16690. this._gl.texParameteri(target, parameter, value);
  16691. };
  16692. /**
  16693. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16694. * @param x defines the x coordinate of the rectangle where pixels must be read
  16695. * @param y defines the y coordinate of the rectangle where pixels must be read
  16696. * @param width defines the width of the rectangle where pixels must be read
  16697. * @param height defines the height of the rectangle where pixels must be read
  16698. * @returns a Uint8Array containing RGBA colors
  16699. */
  16700. Engine.prototype.readPixels = function (x, y, width, height) {
  16701. var data = new Uint8Array(height * width * 4);
  16702. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16703. return data;
  16704. };
  16705. /**
  16706. * Add an externaly attached data from its key.
  16707. * This method call will fail and return false, if such key already exists.
  16708. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16709. * @param key the unique key that identifies the data
  16710. * @param data the data object to associate to the key for this Engine instance
  16711. * @return true if no such key were already present and the data was added successfully, false otherwise
  16712. */
  16713. Engine.prototype.addExternalData = function (key, data) {
  16714. if (!this._externalData) {
  16715. this._externalData = new BABYLON.StringDictionary();
  16716. }
  16717. return this._externalData.add(key, data);
  16718. };
  16719. /**
  16720. * Get an externaly attached data from its key
  16721. * @param key the unique key that identifies the data
  16722. * @return the associated data, if present (can be null), or undefined if not present
  16723. */
  16724. Engine.prototype.getExternalData = function (key) {
  16725. if (!this._externalData) {
  16726. this._externalData = new BABYLON.StringDictionary();
  16727. }
  16728. return this._externalData.get(key);
  16729. };
  16730. /**
  16731. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16732. * @param key the unique key that identifies the data
  16733. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16734. * @return the associated data, can be null if the factory returned null.
  16735. */
  16736. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16737. if (!this._externalData) {
  16738. this._externalData = new BABYLON.StringDictionary();
  16739. }
  16740. return this._externalData.getOrAddWithFactory(key, factory);
  16741. };
  16742. /**
  16743. * Remove an externaly attached data from the Engine instance
  16744. * @param key the unique key that identifies the data
  16745. * @return true if the data was successfully removed, false if it doesn't exist
  16746. */
  16747. Engine.prototype.removeExternalData = function (key) {
  16748. if (!this._externalData) {
  16749. this._externalData = new BABYLON.StringDictionary();
  16750. }
  16751. return this._externalData.remove(key);
  16752. };
  16753. /**
  16754. * Unbind all vertex attributes from the webGL context
  16755. */
  16756. Engine.prototype.unbindAllAttributes = function () {
  16757. if (this._mustWipeVertexAttributes) {
  16758. this._mustWipeVertexAttributes = false;
  16759. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16760. this._gl.disableVertexAttribArray(i);
  16761. this._vertexAttribArraysEnabled[i] = false;
  16762. this._currentBufferPointers[i].active = false;
  16763. }
  16764. return;
  16765. }
  16766. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16767. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16768. continue;
  16769. }
  16770. this._gl.disableVertexAttribArray(i);
  16771. this._vertexAttribArraysEnabled[i] = false;
  16772. this._currentBufferPointers[i].active = false;
  16773. }
  16774. };
  16775. /**
  16776. * 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
  16777. */
  16778. Engine.prototype.releaseEffects = function () {
  16779. for (var name in this._compiledEffects) {
  16780. this._deleteProgram(this._compiledEffects[name]._program);
  16781. }
  16782. this._compiledEffects = {};
  16783. };
  16784. /**
  16785. * Dispose and release all associated resources
  16786. */
  16787. Engine.prototype.dispose = function () {
  16788. this.hideLoadingUI();
  16789. this.stopRenderLoop();
  16790. // Release postProcesses
  16791. while (this.postProcesses.length) {
  16792. this.postProcesses[0].dispose();
  16793. }
  16794. // Empty texture
  16795. if (this._emptyTexture) {
  16796. this._releaseTexture(this._emptyTexture);
  16797. this._emptyTexture = null;
  16798. }
  16799. if (this._emptyCubeTexture) {
  16800. this._releaseTexture(this._emptyCubeTexture);
  16801. this._emptyCubeTexture = null;
  16802. }
  16803. // Rescale PP
  16804. if (this._rescalePostProcess) {
  16805. this._rescalePostProcess.dispose();
  16806. }
  16807. // Release scenes
  16808. while (this.scenes.length) {
  16809. this.scenes[0].dispose();
  16810. }
  16811. // Release audio engine
  16812. if (Engine.audioEngine) {
  16813. Engine.audioEngine.dispose();
  16814. }
  16815. // Release effects
  16816. this.releaseEffects();
  16817. // Unbind
  16818. this.unbindAllAttributes();
  16819. this._boundUniforms = [];
  16820. if (this._dummyFramebuffer) {
  16821. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16822. }
  16823. //WebVR
  16824. this.disableVR();
  16825. // Events
  16826. if (BABYLON.Tools.IsWindowObjectExist()) {
  16827. window.removeEventListener("blur", this._onBlur);
  16828. window.removeEventListener("focus", this._onFocus);
  16829. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16830. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16831. if (this._renderingCanvas) {
  16832. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16833. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16834. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16835. if (!this._doNotHandleContextLost) {
  16836. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16837. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16838. }
  16839. }
  16840. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16841. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16842. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16843. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16844. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16845. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16846. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16847. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16848. if (this._onVrDisplayConnect) {
  16849. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16850. if (this._onVrDisplayDisconnect) {
  16851. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16852. }
  16853. if (this._onVrDisplayPresentChange) {
  16854. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16855. }
  16856. this._onVrDisplayConnect = null;
  16857. this._onVrDisplayDisconnect = null;
  16858. }
  16859. }
  16860. // Remove from Instances
  16861. var index = Engine.Instances.indexOf(this);
  16862. if (index >= 0) {
  16863. Engine.Instances.splice(index, 1);
  16864. }
  16865. this._workingCanvas = null;
  16866. this._workingContext = null;
  16867. this._currentBufferPointers = [];
  16868. this._renderingCanvas = null;
  16869. this._currentProgram = null;
  16870. this._bindedRenderFunction = null;
  16871. this.onResizeObservable.clear();
  16872. this.onCanvasBlurObservable.clear();
  16873. this.onCanvasFocusObservable.clear();
  16874. this.onCanvasPointerOutObservable.clear();
  16875. this.onBeginFrameObservable.clear();
  16876. this.onEndFrameObservable.clear();
  16877. BABYLON.Effect.ResetCache();
  16878. // Abort active requests
  16879. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16880. var request = _a[_i];
  16881. request.abort();
  16882. }
  16883. };
  16884. // Loading screen
  16885. /**
  16886. * Display the loading screen
  16887. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16888. */
  16889. Engine.prototype.displayLoadingUI = function () {
  16890. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16891. return;
  16892. }
  16893. var loadingScreen = this.loadingScreen;
  16894. if (loadingScreen) {
  16895. loadingScreen.displayLoadingUI();
  16896. }
  16897. };
  16898. /**
  16899. * Hide the loading screen
  16900. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16901. */
  16902. Engine.prototype.hideLoadingUI = function () {
  16903. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16904. return;
  16905. }
  16906. var loadingScreen = this.loadingScreen;
  16907. if (loadingScreen) {
  16908. loadingScreen.hideLoadingUI();
  16909. }
  16910. };
  16911. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16912. /**
  16913. * Gets the current loading screen object
  16914. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16915. */
  16916. get: function () {
  16917. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16918. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16919. return this._loadingScreen;
  16920. },
  16921. /**
  16922. * Sets the current loading screen object
  16923. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16924. */
  16925. set: function (loadingScreen) {
  16926. this._loadingScreen = loadingScreen;
  16927. },
  16928. enumerable: true,
  16929. configurable: true
  16930. });
  16931. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16932. /**
  16933. * Sets the current loading screen text
  16934. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16935. */
  16936. set: function (text) {
  16937. this.loadingScreen.loadingUIText = text;
  16938. },
  16939. enumerable: true,
  16940. configurable: true
  16941. });
  16942. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16943. /**
  16944. * Sets the current loading screen background color
  16945. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16946. */
  16947. set: function (color) {
  16948. this.loadingScreen.loadingUIBackgroundColor = color;
  16949. },
  16950. enumerable: true,
  16951. configurable: true
  16952. });
  16953. /**
  16954. * Attach a new callback raised when context lost event is fired
  16955. * @param callback defines the callback to call
  16956. */
  16957. Engine.prototype.attachContextLostEvent = function (callback) {
  16958. if (this._renderingCanvas) {
  16959. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16960. }
  16961. };
  16962. /**
  16963. * Attach a new callback raised when context restored event is fired
  16964. * @param callback defines the callback to call
  16965. */
  16966. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16967. if (this._renderingCanvas) {
  16968. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16969. }
  16970. };
  16971. /**
  16972. * Gets the source code of the vertex shader associated with a specific webGL program
  16973. * @param program defines the program to use
  16974. * @returns a string containing the source code of the vertex shader associated with the program
  16975. */
  16976. Engine.prototype.getVertexShaderSource = function (program) {
  16977. var shaders = this._gl.getAttachedShaders(program);
  16978. if (!shaders) {
  16979. return null;
  16980. }
  16981. return this._gl.getShaderSource(shaders[0]);
  16982. };
  16983. /**
  16984. * Gets the source code of the fragment shader associated with a specific webGL program
  16985. * @param program defines the program to use
  16986. * @returns a string containing the source code of the fragment shader associated with the program
  16987. */
  16988. Engine.prototype.getFragmentShaderSource = function (program) {
  16989. var shaders = this._gl.getAttachedShaders(program);
  16990. if (!shaders) {
  16991. return null;
  16992. }
  16993. return this._gl.getShaderSource(shaders[1]);
  16994. };
  16995. /**
  16996. * Get the current error code of the webGL context
  16997. * @returns the error code
  16998. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16999. */
  17000. Engine.prototype.getError = function () {
  17001. return this._gl.getError();
  17002. };
  17003. // FPS
  17004. /**
  17005. * Gets the current framerate
  17006. * @returns a number representing the framerate
  17007. */
  17008. Engine.prototype.getFps = function () {
  17009. return this._fps;
  17010. };
  17011. /**
  17012. * Gets the time spent between current and previous frame
  17013. * @returns a number representing the delta time in ms
  17014. */
  17015. Engine.prototype.getDeltaTime = function () {
  17016. return this._deltaTime;
  17017. };
  17018. Engine.prototype._measureFps = function () {
  17019. this._performanceMonitor.sampleFrame();
  17020. this._fps = this._performanceMonitor.averageFPS;
  17021. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17022. };
  17023. /** @hidden */
  17024. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  17025. if (faceIndex === void 0) { faceIndex = -1; }
  17026. if (level === void 0) { level = 0; }
  17027. var gl = this._gl;
  17028. if (!this._dummyFramebuffer) {
  17029. var dummy = gl.createFramebuffer();
  17030. if (!dummy) {
  17031. throw new Error("Unable to create dummy framebuffer");
  17032. }
  17033. this._dummyFramebuffer = dummy;
  17034. }
  17035. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17036. if (faceIndex > -1) {
  17037. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17038. }
  17039. else {
  17040. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17041. }
  17042. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17043. var buffer;
  17044. switch (readType) {
  17045. case gl.UNSIGNED_BYTE:
  17046. buffer = new Uint8Array(4 * width * height);
  17047. readType = gl.UNSIGNED_BYTE;
  17048. break;
  17049. default:
  17050. buffer = new Float32Array(4 * width * height);
  17051. readType = gl.FLOAT;
  17052. break;
  17053. }
  17054. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17055. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17056. return buffer;
  17057. };
  17058. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17059. if (this._webGLVersion > 1) {
  17060. return this._caps.colorBufferFloat;
  17061. }
  17062. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17063. };
  17064. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17065. if (this._webGLVersion > 1) {
  17066. return this._caps.colorBufferFloat;
  17067. }
  17068. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17069. };
  17070. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17071. Engine.prototype._canRenderToFramebuffer = function (type) {
  17072. var gl = this._gl;
  17073. //clear existing errors
  17074. while (gl.getError() !== gl.NO_ERROR) { }
  17075. var successful = true;
  17076. var texture = gl.createTexture();
  17077. gl.bindTexture(gl.TEXTURE_2D, texture);
  17078. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17079. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17080. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17081. var fb = gl.createFramebuffer();
  17082. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17083. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17084. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17085. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17086. successful = successful && (gl.getError() === gl.NO_ERROR);
  17087. //try render by clearing frame buffer's color buffer
  17088. if (successful) {
  17089. gl.clear(gl.COLOR_BUFFER_BIT);
  17090. successful = successful && (gl.getError() === gl.NO_ERROR);
  17091. }
  17092. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17093. if (successful) {
  17094. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17095. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17096. var readFormat = gl.RGBA;
  17097. var readType = gl.UNSIGNED_BYTE;
  17098. var buffer = new Uint8Array(4);
  17099. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17100. successful = successful && (gl.getError() === gl.NO_ERROR);
  17101. }
  17102. //clean up
  17103. gl.deleteTexture(texture);
  17104. gl.deleteFramebuffer(fb);
  17105. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17106. //clear accumulated errors
  17107. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17108. return successful;
  17109. };
  17110. /** @hidden */
  17111. Engine.prototype._getWebGLTextureType = function (type) {
  17112. if (type === Engine.TEXTURETYPE_FLOAT) {
  17113. return this._gl.FLOAT;
  17114. }
  17115. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17116. // Add Half Float Constant.
  17117. return this._gl.HALF_FLOAT_OES;
  17118. }
  17119. return this._gl.UNSIGNED_BYTE;
  17120. };
  17121. ;
  17122. Engine.prototype._getInternalFormat = function (format) {
  17123. var internalFormat = this._gl.RGBA;
  17124. switch (format) {
  17125. case Engine.TEXTUREFORMAT_ALPHA:
  17126. internalFormat = this._gl.ALPHA;
  17127. break;
  17128. case Engine.TEXTUREFORMAT_LUMINANCE:
  17129. internalFormat = this._gl.LUMINANCE;
  17130. break;
  17131. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17132. internalFormat = this._gl.LUMINANCE_ALPHA;
  17133. break;
  17134. case Engine.TEXTUREFORMAT_RGB:
  17135. internalFormat = this._gl.RGB;
  17136. break;
  17137. case Engine.TEXTUREFORMAT_RGBA:
  17138. internalFormat = this._gl.RGBA;
  17139. break;
  17140. case Engine.TEXTUREFORMAT_R:
  17141. internalFormat = this._gl.RED;
  17142. break;
  17143. case Engine.TEXTUREFORMAT_RG:
  17144. internalFormat = this._gl.RG;
  17145. break;
  17146. }
  17147. return internalFormat;
  17148. };
  17149. /** @hidden */
  17150. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17151. if (this._webGLVersion === 1) {
  17152. if (format !== undefined) {
  17153. switch (format) {
  17154. case Engine.TEXTUREFORMAT_LUMINANCE:
  17155. return this._gl.LUMINANCE;
  17156. case Engine.TEXTUREFORMAT_ALPHA:
  17157. return this._gl.ALPHA;
  17158. }
  17159. }
  17160. return this._gl.RGBA;
  17161. }
  17162. if (type === Engine.TEXTURETYPE_FLOAT) {
  17163. if (format !== undefined) {
  17164. switch (format) {
  17165. case Engine.TEXTUREFORMAT_R:
  17166. return this._gl.R32F;
  17167. case Engine.TEXTUREFORMAT_RG:
  17168. return this._gl.RG32F;
  17169. case Engine.TEXTUREFORMAT_RGB:
  17170. return this._gl.RGB32F;
  17171. }
  17172. }
  17173. return this._gl.RGBA32F;
  17174. }
  17175. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17176. if (format) {
  17177. switch (format) {
  17178. case Engine.TEXTUREFORMAT_R:
  17179. return this._gl.R16F;
  17180. case Engine.TEXTUREFORMAT_RG:
  17181. return this._gl.RG16F;
  17182. case Engine.TEXTUREFORMAT_RGB:
  17183. return this._gl.RGB16F;
  17184. }
  17185. }
  17186. return this._gl.RGBA16F;
  17187. }
  17188. if (format !== undefined) {
  17189. switch (format) {
  17190. case Engine.TEXTUREFORMAT_LUMINANCE:
  17191. return this._gl.LUMINANCE;
  17192. case Engine.TEXTUREFORMAT_RGB:
  17193. return this._gl.RGB;
  17194. case Engine.TEXTUREFORMAT_R:
  17195. return this._gl.R8;
  17196. case Engine.TEXTUREFORMAT_RG:
  17197. return this._gl.RG8;
  17198. case Engine.TEXTUREFORMAT_ALPHA:
  17199. return this._gl.ALPHA;
  17200. }
  17201. }
  17202. return this._gl.RGBA;
  17203. };
  17204. ;
  17205. /** @hidden */
  17206. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17207. if (type === Engine.TEXTURETYPE_FLOAT) {
  17208. return this._gl.RGBA32F;
  17209. }
  17210. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17211. return this._gl.RGBA16F;
  17212. }
  17213. return this._gl.RGBA8;
  17214. };
  17215. ;
  17216. /**
  17217. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17218. * @return the new query
  17219. */
  17220. Engine.prototype.createQuery = function () {
  17221. return this._gl.createQuery();
  17222. };
  17223. /**
  17224. * Delete and release a webGL query
  17225. * @param query defines the query to delete
  17226. * @return the current engine
  17227. */
  17228. Engine.prototype.deleteQuery = function (query) {
  17229. this._gl.deleteQuery(query);
  17230. return this;
  17231. };
  17232. /**
  17233. * Check if a given query has resolved and got its value
  17234. * @param query defines the query to check
  17235. * @returns true if the query got its value
  17236. */
  17237. Engine.prototype.isQueryResultAvailable = function (query) {
  17238. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17239. };
  17240. /**
  17241. * Gets the value of a given query
  17242. * @param query defines the query to check
  17243. * @returns the value of the query
  17244. */
  17245. Engine.prototype.getQueryResult = function (query) {
  17246. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17247. };
  17248. /**
  17249. * Initiates an occlusion query
  17250. * @param algorithmType defines the algorithm to use
  17251. * @param query defines the query to use
  17252. * @returns the current engine
  17253. * @see http://doc.babylonjs.com/features/occlusionquery
  17254. */
  17255. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17256. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17257. this._gl.beginQuery(glAlgorithm, query);
  17258. return this;
  17259. };
  17260. /**
  17261. * Ends an occlusion query
  17262. * @see http://doc.babylonjs.com/features/occlusionquery
  17263. * @param algorithmType defines the algorithm to use
  17264. * @returns the current engine
  17265. */
  17266. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17267. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17268. this._gl.endQuery(glAlgorithm);
  17269. return this;
  17270. };
  17271. /* Time queries */
  17272. Engine.prototype._createTimeQuery = function () {
  17273. var timerQuery = this._caps.timerQuery;
  17274. if (timerQuery.createQueryEXT) {
  17275. return timerQuery.createQueryEXT();
  17276. }
  17277. return this.createQuery();
  17278. };
  17279. Engine.prototype._deleteTimeQuery = function (query) {
  17280. var timerQuery = this._caps.timerQuery;
  17281. if (timerQuery.deleteQueryEXT) {
  17282. timerQuery.deleteQueryEXT(query);
  17283. return;
  17284. }
  17285. this.deleteQuery(query);
  17286. };
  17287. Engine.prototype._getTimeQueryResult = function (query) {
  17288. var timerQuery = this._caps.timerQuery;
  17289. if (timerQuery.getQueryObjectEXT) {
  17290. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17291. }
  17292. return this.getQueryResult(query);
  17293. };
  17294. Engine.prototype._getTimeQueryAvailability = function (query) {
  17295. var timerQuery = this._caps.timerQuery;
  17296. if (timerQuery.getQueryObjectEXT) {
  17297. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17298. }
  17299. return this.isQueryResultAvailable(query);
  17300. };
  17301. /**
  17302. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17303. * Please note that only one query can be issued at a time
  17304. * @returns a time token used to track the time span
  17305. */
  17306. Engine.prototype.startTimeQuery = function () {
  17307. var timerQuery = this._caps.timerQuery;
  17308. if (!timerQuery) {
  17309. return null;
  17310. }
  17311. var token = new BABYLON._TimeToken();
  17312. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17313. if (this._caps.canUseTimestampForTimerQuery) {
  17314. token._startTimeQuery = this._createTimeQuery();
  17315. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17316. }
  17317. else {
  17318. if (this._currentNonTimestampToken) {
  17319. return this._currentNonTimestampToken;
  17320. }
  17321. token._timeElapsedQuery = this._createTimeQuery();
  17322. if (timerQuery.beginQueryEXT) {
  17323. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17324. }
  17325. else {
  17326. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17327. }
  17328. this._currentNonTimestampToken = token;
  17329. }
  17330. return token;
  17331. };
  17332. /**
  17333. * Ends a time query
  17334. * @param token defines the token used to measure the time span
  17335. * @returns the time spent (in ns)
  17336. */
  17337. Engine.prototype.endTimeQuery = function (token) {
  17338. var timerQuery = this._caps.timerQuery;
  17339. if (!timerQuery || !token) {
  17340. return -1;
  17341. }
  17342. if (this._caps.canUseTimestampForTimerQuery) {
  17343. if (!token._startTimeQuery) {
  17344. return -1;
  17345. }
  17346. if (!token._endTimeQuery) {
  17347. token._endTimeQuery = this._createTimeQuery();
  17348. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17349. }
  17350. }
  17351. else if (!token._timeElapsedQueryEnded) {
  17352. if (!token._timeElapsedQuery) {
  17353. return -1;
  17354. }
  17355. if (timerQuery.endQueryEXT) {
  17356. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17357. }
  17358. else {
  17359. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17360. }
  17361. token._timeElapsedQueryEnded = true;
  17362. }
  17363. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17364. var available = false;
  17365. if (token._endTimeQuery) {
  17366. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17367. }
  17368. else if (token._timeElapsedQuery) {
  17369. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17370. }
  17371. if (available && !disjoint) {
  17372. var result = 0;
  17373. if (this._caps.canUseTimestampForTimerQuery) {
  17374. if (!token._startTimeQuery || !token._endTimeQuery) {
  17375. return -1;
  17376. }
  17377. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17378. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17379. result = timeEnd - timeStart;
  17380. this._deleteTimeQuery(token._startTimeQuery);
  17381. this._deleteTimeQuery(token._endTimeQuery);
  17382. token._startTimeQuery = null;
  17383. token._endTimeQuery = null;
  17384. }
  17385. else {
  17386. if (!token._timeElapsedQuery) {
  17387. return -1;
  17388. }
  17389. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17390. this._deleteTimeQuery(token._timeElapsedQuery);
  17391. token._timeElapsedQuery = null;
  17392. token._timeElapsedQueryEnded = false;
  17393. this._currentNonTimestampToken = null;
  17394. }
  17395. return result;
  17396. }
  17397. return -1;
  17398. };
  17399. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17400. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17401. };
  17402. // Transform feedback
  17403. /**
  17404. * Creates a webGL transform feedback object
  17405. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17406. * @returns the webGL transform feedback object
  17407. */
  17408. Engine.prototype.createTransformFeedback = function () {
  17409. return this._gl.createTransformFeedback();
  17410. };
  17411. /**
  17412. * Delete a webGL transform feedback object
  17413. * @param value defines the webGL transform feedback object to delete
  17414. */
  17415. Engine.prototype.deleteTransformFeedback = function (value) {
  17416. this._gl.deleteTransformFeedback(value);
  17417. };
  17418. /**
  17419. * Bind a webGL transform feedback object to the webgl context
  17420. * @param value defines the webGL transform feedback object to bind
  17421. */
  17422. Engine.prototype.bindTransformFeedback = function (value) {
  17423. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17424. };
  17425. /**
  17426. * Begins a transform feedback operation
  17427. * @param usePoints defines if points or triangles must be used
  17428. */
  17429. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17430. if (usePoints === void 0) { usePoints = true; }
  17431. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17432. };
  17433. /**
  17434. * Ends a transform feedback operation
  17435. */
  17436. Engine.prototype.endTransformFeedback = function () {
  17437. this._gl.endTransformFeedback();
  17438. };
  17439. /**
  17440. * Specify the varyings to use with transform feedback
  17441. * @param program defines the associated webGL program
  17442. * @param value defines the list of strings representing the varying names
  17443. */
  17444. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17445. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17446. };
  17447. /**
  17448. * Bind a webGL buffer for a transform feedback operation
  17449. * @param value defines the webGL buffer to bind
  17450. */
  17451. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17452. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17453. };
  17454. /** @hidden */
  17455. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17456. var _this = this;
  17457. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17458. this._activeRequests.push(request);
  17459. request.onCompleteObservable.add(function (request) {
  17460. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17461. });
  17462. return request;
  17463. };
  17464. /** @hidden */
  17465. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17466. var _this = this;
  17467. return new Promise(function (resolve, reject) {
  17468. _this._loadFile(url, function (data) {
  17469. resolve(data);
  17470. }, undefined, database, useArrayBuffer, function (request, exception) {
  17471. reject(exception);
  17472. });
  17473. });
  17474. };
  17475. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17476. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17477. var onload = function (data) {
  17478. loadedFiles[index] = data;
  17479. loadedFiles._internalCount++;
  17480. if (loadedFiles._internalCount === 6) {
  17481. onfinish(loadedFiles);
  17482. }
  17483. };
  17484. var onerror = function (request, exception) {
  17485. if (onErrorCallBack && request) {
  17486. onErrorCallBack(request.status + " " + request.statusText, exception);
  17487. }
  17488. };
  17489. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17490. };
  17491. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17492. if (onError === void 0) { onError = null; }
  17493. var loadedFiles = [];
  17494. loadedFiles._internalCount = 0;
  17495. for (var index = 0; index < 6; index++) {
  17496. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17497. }
  17498. };
  17499. // Statics
  17500. /**
  17501. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17502. * @returns true if the engine can be created
  17503. * @ignorenaming
  17504. */
  17505. Engine.isSupported = function () {
  17506. try {
  17507. var tempcanvas = document.createElement("canvas");
  17508. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17509. return gl != null && !!window.WebGLRenderingContext;
  17510. }
  17511. catch (e) {
  17512. return false;
  17513. }
  17514. };
  17515. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17516. Engine.ExceptionList = [
  17517. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17518. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17519. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17520. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17521. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17522. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17523. ];
  17524. /** Gets the list of created engines */
  17525. Engine.Instances = new Array();
  17526. // Const statics
  17527. Engine._ALPHA_DISABLE = 0;
  17528. Engine._ALPHA_ADD = 1;
  17529. Engine._ALPHA_COMBINE = 2;
  17530. Engine._ALPHA_SUBTRACT = 3;
  17531. Engine._ALPHA_MULTIPLY = 4;
  17532. Engine._ALPHA_MAXIMIZED = 5;
  17533. Engine._ALPHA_ONEONE = 6;
  17534. Engine._ALPHA_PREMULTIPLIED = 7;
  17535. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17536. Engine._ALPHA_INTERPOLATE = 9;
  17537. Engine._ALPHA_SCREENMODE = 10;
  17538. Engine._DELAYLOADSTATE_NONE = 0;
  17539. Engine._DELAYLOADSTATE_LOADED = 1;
  17540. Engine._DELAYLOADSTATE_LOADING = 2;
  17541. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17542. Engine._TEXTUREFORMAT_ALPHA = 0;
  17543. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17544. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17545. Engine._TEXTUREFORMAT_RGB = 4;
  17546. Engine._TEXTUREFORMAT_RGBA = 5;
  17547. Engine._TEXTUREFORMAT_R = 6;
  17548. Engine._TEXTUREFORMAT_RG = 7;
  17549. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17550. Engine._TEXTURETYPE_FLOAT = 1;
  17551. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17552. // Depht or Stencil test Constants.
  17553. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17554. 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.
  17555. 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.
  17556. 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.
  17557. 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.
  17558. 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.
  17559. 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.
  17560. 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.
  17561. // Stencil Actions Constants.
  17562. Engine._KEEP = 0x1E00;
  17563. Engine._REPLACE = 0x1E01;
  17564. Engine._INCR = 0x1E02;
  17565. Engine._DECR = 0x1E03;
  17566. Engine._INVERT = 0x150A;
  17567. Engine._INCR_WRAP = 0x8507;
  17568. Engine._DECR_WRAP = 0x8508;
  17569. // Texture rescaling mode
  17570. Engine._SCALEMODE_FLOOR = 1;
  17571. Engine._SCALEMODE_NEAREST = 2;
  17572. Engine._SCALEMODE_CEILING = 3;
  17573. // Updatable statics so stick with vars here
  17574. /**
  17575. * Gets or sets the epsilon value used by collision engine
  17576. */
  17577. Engine.CollisionsEpsilon = 0.001;
  17578. /**
  17579. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17580. */
  17581. Engine.CodeRepository = "src/";
  17582. /**
  17583. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17584. */
  17585. Engine.ShadersRepository = "src/Shaders/";
  17586. return Engine;
  17587. }());
  17588. BABYLON.Engine = Engine;
  17589. })(BABYLON || (BABYLON = {}));
  17590. //# sourceMappingURL=babylon.engine.js.map
  17591. var BABYLON;
  17592. (function (BABYLON) {
  17593. /**
  17594. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17595. */
  17596. var Node = /** @class */ (function () {
  17597. /**
  17598. * Creates a new Node
  17599. * @param {string} name - the name and id to be given to this node
  17600. * @param {BABYLON.Scene} the scene this node will be added to
  17601. */
  17602. function Node(name, scene) {
  17603. if (scene === void 0) { scene = null; }
  17604. /**
  17605. * Gets or sets a string used to store user defined state for the node
  17606. */
  17607. this.state = "";
  17608. /**
  17609. * Gets or sets an object used to store user defined information for the node
  17610. */
  17611. this.metadata = null;
  17612. /**
  17613. * Gets or sets a boolean used to define if the node must be serialized
  17614. */
  17615. this.doNotSerialize = false;
  17616. /** @hidden */
  17617. this._isDisposed = false;
  17618. /**
  17619. * Gets a list of Animations associated with the node
  17620. */
  17621. this.animations = new Array();
  17622. this._ranges = {};
  17623. this._isEnabled = true;
  17624. this._isReady = true;
  17625. /** @hidden */
  17626. this._currentRenderId = -1;
  17627. this._parentRenderId = -1;
  17628. this._childRenderId = -1;
  17629. this._animationPropertiesOverride = null;
  17630. /**
  17631. * An event triggered when the mesh is disposed
  17632. */
  17633. this.onDisposeObservable = new BABYLON.Observable();
  17634. // Behaviors
  17635. this._behaviors = new Array();
  17636. this.name = name;
  17637. this.id = name;
  17638. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17639. this.uniqueId = this._scene.getUniqueId();
  17640. this._initCache();
  17641. }
  17642. /**
  17643. * Gets a boolean indicating if the node has been disposed
  17644. * @returns true if the node was disposed
  17645. */
  17646. Node.prototype.isDisposed = function () {
  17647. return this._isDisposed;
  17648. };
  17649. Object.defineProperty(Node.prototype, "parent", {
  17650. get: function () {
  17651. return this._parentNode;
  17652. },
  17653. /**
  17654. * Gets or sets the parent of the node
  17655. */
  17656. set: function (parent) {
  17657. if (this._parentNode === parent) {
  17658. return;
  17659. }
  17660. // Remove self from list of children of parent
  17661. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17662. var index = this._parentNode._children.indexOf(this);
  17663. if (index !== -1) {
  17664. this._parentNode._children.splice(index, 1);
  17665. }
  17666. }
  17667. // Store new parent
  17668. this._parentNode = parent;
  17669. // Add as child to new parent
  17670. if (this._parentNode) {
  17671. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17672. this._parentNode._children = new Array();
  17673. }
  17674. this._parentNode._children.push(this);
  17675. }
  17676. },
  17677. enumerable: true,
  17678. configurable: true
  17679. });
  17680. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17681. /**
  17682. * Gets or sets the animation properties override
  17683. */
  17684. get: function () {
  17685. if (!this._animationPropertiesOverride) {
  17686. return this._scene.animationPropertiesOverride;
  17687. }
  17688. return this._animationPropertiesOverride;
  17689. },
  17690. set: function (value) {
  17691. this._animationPropertiesOverride = value;
  17692. },
  17693. enumerable: true,
  17694. configurable: true
  17695. });
  17696. /**
  17697. * Gets a string idenfifying the name of the class
  17698. * @returns "Node" string
  17699. */
  17700. Node.prototype.getClassName = function () {
  17701. return "Node";
  17702. };
  17703. Object.defineProperty(Node.prototype, "onDispose", {
  17704. /**
  17705. * Sets a callback that will be raised when the node will be disposed
  17706. */
  17707. set: function (callback) {
  17708. if (this._onDisposeObserver) {
  17709. this.onDisposeObservable.remove(this._onDisposeObserver);
  17710. }
  17711. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17712. },
  17713. enumerable: true,
  17714. configurable: true
  17715. });
  17716. /**
  17717. * Gets the scene of the node
  17718. * @returns a {BABYLON.Scene}
  17719. */
  17720. Node.prototype.getScene = function () {
  17721. return this._scene;
  17722. };
  17723. /**
  17724. * Gets the engine of the node
  17725. * @returns a {BABYLON.Engine}
  17726. */
  17727. Node.prototype.getEngine = function () {
  17728. return this._scene.getEngine();
  17729. };
  17730. /**
  17731. * Attach a behavior to the node
  17732. * @see http://doc.babylonjs.com/features/behaviour
  17733. * @param behavior defines the behavior to attach
  17734. * @returns the current Node
  17735. */
  17736. Node.prototype.addBehavior = function (behavior) {
  17737. var _this = this;
  17738. var index = this._behaviors.indexOf(behavior);
  17739. if (index !== -1) {
  17740. return this;
  17741. }
  17742. behavior.init();
  17743. if (this._scene.isLoading) {
  17744. // We defer the attach when the scene will be loaded
  17745. this._scene.onDataLoadedObservable.addOnce(function () {
  17746. behavior.attach(_this);
  17747. });
  17748. }
  17749. else {
  17750. behavior.attach(this);
  17751. }
  17752. this._behaviors.push(behavior);
  17753. return this;
  17754. };
  17755. /**
  17756. * Remove an attached behavior
  17757. * @see http://doc.babylonjs.com/features/behaviour
  17758. * @param behavior defines the behavior to attach
  17759. * @returns the current Node
  17760. */
  17761. Node.prototype.removeBehavior = function (behavior) {
  17762. var index = this._behaviors.indexOf(behavior);
  17763. if (index === -1) {
  17764. return this;
  17765. }
  17766. this._behaviors[index].detach();
  17767. this._behaviors.splice(index, 1);
  17768. return this;
  17769. };
  17770. Object.defineProperty(Node.prototype, "behaviors", {
  17771. /**
  17772. * Gets the list of attached behaviors
  17773. * @see http://doc.babylonjs.com/features/behaviour
  17774. */
  17775. get: function () {
  17776. return this._behaviors;
  17777. },
  17778. enumerable: true,
  17779. configurable: true
  17780. });
  17781. /**
  17782. * Gets an attached behavior by name
  17783. * @param name defines the name of the behavior to look for
  17784. * @see http://doc.babylonjs.com/features/behaviour
  17785. * @returns null if behavior was not found else the requested behavior
  17786. */
  17787. Node.prototype.getBehaviorByName = function (name) {
  17788. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17789. var behavior = _a[_i];
  17790. if (behavior.name === name) {
  17791. return behavior;
  17792. }
  17793. }
  17794. return null;
  17795. };
  17796. /**
  17797. * Returns the world matrix of the node
  17798. * @returns a matrix containing the node's world matrix
  17799. */
  17800. Node.prototype.getWorldMatrix = function () {
  17801. return BABYLON.Matrix.Identity();
  17802. };
  17803. /** @hidden */
  17804. Node.prototype._getWorldMatrixDeterminant = function () {
  17805. return 1;
  17806. };
  17807. // override it in derived class if you add new variables to the cache
  17808. // and call the parent class method
  17809. /** @hidden */
  17810. Node.prototype._initCache = function () {
  17811. this._cache = {};
  17812. this._cache.parent = undefined;
  17813. };
  17814. /** @hidden */
  17815. Node.prototype.updateCache = function (force) {
  17816. if (!force && this.isSynchronized())
  17817. return;
  17818. this._cache.parent = this.parent;
  17819. this._updateCache();
  17820. };
  17821. // override it in derived class if you add new variables to the cache
  17822. // and call the parent class method if !ignoreParentClass
  17823. /** @hidden */
  17824. Node.prototype._updateCache = function (ignoreParentClass) {
  17825. };
  17826. // override it in derived class if you add new variables to the cache
  17827. /** @hidden */
  17828. Node.prototype._isSynchronized = function () {
  17829. return true;
  17830. };
  17831. /** @hidden */
  17832. Node.prototype._markSyncedWithParent = function () {
  17833. if (this.parent) {
  17834. this._parentRenderId = this.parent._childRenderId;
  17835. }
  17836. };
  17837. /** @hidden */
  17838. Node.prototype.isSynchronizedWithParent = function () {
  17839. if (!this.parent) {
  17840. return true;
  17841. }
  17842. if (this._parentRenderId !== this.parent._childRenderId) {
  17843. return false;
  17844. }
  17845. return this.parent.isSynchronized();
  17846. };
  17847. /** @hidden */
  17848. Node.prototype.isSynchronized = function (updateCache) {
  17849. var check = this.hasNewParent();
  17850. check = check || !this.isSynchronizedWithParent();
  17851. check = check || !this._isSynchronized();
  17852. if (updateCache)
  17853. this.updateCache(true);
  17854. return !check;
  17855. };
  17856. /** @hidden */
  17857. Node.prototype.hasNewParent = function (update) {
  17858. if (this._cache.parent === this.parent)
  17859. return false;
  17860. if (update)
  17861. this._cache.parent = this.parent;
  17862. return true;
  17863. };
  17864. /**
  17865. * Is this node ready to be used/rendered
  17866. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17867. * @return true if the node is ready
  17868. */
  17869. Node.prototype.isReady = function (completeCheck) {
  17870. if (completeCheck === void 0) { completeCheck = false; }
  17871. return this._isReady;
  17872. };
  17873. /**
  17874. * Is this node enabled?
  17875. * 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
  17876. * @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
  17877. * @return whether this node (and its parent) is enabled
  17878. */
  17879. Node.prototype.isEnabled = function (checkAncestors) {
  17880. if (checkAncestors === void 0) { checkAncestors = true; }
  17881. if (checkAncestors === false) {
  17882. return this._isEnabled;
  17883. }
  17884. if (this._isEnabled === false) {
  17885. return false;
  17886. }
  17887. if (this.parent !== undefined && this.parent !== null) {
  17888. return this.parent.isEnabled(checkAncestors);
  17889. }
  17890. return true;
  17891. };
  17892. /**
  17893. * Set the enabled state of this node
  17894. * @param value defines the new enabled state
  17895. */
  17896. Node.prototype.setEnabled = function (value) {
  17897. this._isEnabled = value;
  17898. };
  17899. /**
  17900. * Is this node a descendant of the given node?
  17901. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17902. * @param ancestor defines the parent node to inspect
  17903. * @returns a boolean indicating if this node is a descendant of the given node
  17904. */
  17905. Node.prototype.isDescendantOf = function (ancestor) {
  17906. if (this.parent) {
  17907. if (this.parent === ancestor) {
  17908. return true;
  17909. }
  17910. return this.parent.isDescendantOf(ancestor);
  17911. }
  17912. return false;
  17913. };
  17914. /** @hidden */
  17915. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17916. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17917. if (!this._children) {
  17918. return;
  17919. }
  17920. for (var index = 0; index < this._children.length; index++) {
  17921. var item = this._children[index];
  17922. if (!predicate || predicate(item)) {
  17923. results.push(item);
  17924. }
  17925. if (!directDescendantsOnly) {
  17926. item._getDescendants(results, false, predicate);
  17927. }
  17928. }
  17929. };
  17930. /**
  17931. * Will return all nodes that have this node as ascendant
  17932. * @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
  17933. * @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
  17934. * @return all children nodes of all types
  17935. */
  17936. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17937. var results = new Array();
  17938. this._getDescendants(results, directDescendantsOnly, predicate);
  17939. return results;
  17940. };
  17941. /**
  17942. * Get all child-meshes of this node
  17943. * @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
  17944. * @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
  17945. * @returns an array of {BABYLON.AbstractMesh}
  17946. */
  17947. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17948. var results = [];
  17949. this._getDescendants(results, directDescendantsOnly, function (node) {
  17950. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17951. });
  17952. return results;
  17953. };
  17954. /**
  17955. * Get all child-transformNodes of this node
  17956. * @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
  17957. * @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
  17958. * @returns an array of {BABYLON.TransformNode}
  17959. */
  17960. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17961. var results = [];
  17962. this._getDescendants(results, directDescendantsOnly, function (node) {
  17963. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17964. });
  17965. return results;
  17966. };
  17967. /**
  17968. * Get all direct children of this node
  17969. * @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
  17970. * @returns an array of {BABYLON.Node}
  17971. */
  17972. Node.prototype.getChildren = function (predicate) {
  17973. return this.getDescendants(true, predicate);
  17974. };
  17975. /** @hidden */
  17976. Node.prototype._setReady = function (state) {
  17977. if (state === this._isReady) {
  17978. return;
  17979. }
  17980. if (!state) {
  17981. this._isReady = false;
  17982. return;
  17983. }
  17984. if (this.onReady) {
  17985. this.onReady(this);
  17986. }
  17987. this._isReady = true;
  17988. };
  17989. /**
  17990. * Get an animation by name
  17991. * @param name defines the name of the animation to look for
  17992. * @returns null if not found else the requested animation
  17993. */
  17994. Node.prototype.getAnimationByName = function (name) {
  17995. for (var i = 0; i < this.animations.length; i++) {
  17996. var animation = this.animations[i];
  17997. if (animation.name === name) {
  17998. return animation;
  17999. }
  18000. }
  18001. return null;
  18002. };
  18003. /**
  18004. * Creates an animation range for this node
  18005. * @param name defines the name of the range
  18006. * @param from defines the starting key
  18007. * @param to defines the end key
  18008. */
  18009. Node.prototype.createAnimationRange = function (name, from, to) {
  18010. // check name not already in use
  18011. if (!this._ranges[name]) {
  18012. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18013. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18014. if (this.animations[i]) {
  18015. this.animations[i].createRange(name, from, to);
  18016. }
  18017. }
  18018. }
  18019. };
  18020. /**
  18021. * Delete a specific animation range
  18022. * @param name defines the name of the range to delete
  18023. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18024. */
  18025. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18026. if (deleteFrames === void 0) { deleteFrames = true; }
  18027. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18028. if (this.animations[i]) {
  18029. this.animations[i].deleteRange(name, deleteFrames);
  18030. }
  18031. }
  18032. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18033. };
  18034. /**
  18035. * Get an animation range by name
  18036. * @param name defines the name of the animation range to look for
  18037. * @returns null if not found else the requested animation range
  18038. */
  18039. Node.prototype.getAnimationRange = function (name) {
  18040. return this._ranges[name];
  18041. };
  18042. /**
  18043. * Will start the animation sequence
  18044. * @param name defines the range frames for animation sequence
  18045. * @param loop defines if the animation should loop (false by default)
  18046. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18047. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18048. * @returns the object created for this animation. If range does not exist, it will return null
  18049. */
  18050. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18051. var range = this.getAnimationRange(name);
  18052. if (!range) {
  18053. return null;
  18054. }
  18055. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18056. };
  18057. /**
  18058. * Serialize animation ranges into a JSON compatible object
  18059. * @returns serialization object
  18060. */
  18061. Node.prototype.serializeAnimationRanges = function () {
  18062. var serializationRanges = [];
  18063. for (var name in this._ranges) {
  18064. var localRange = this._ranges[name];
  18065. if (!localRange) {
  18066. continue;
  18067. }
  18068. var range = {};
  18069. range.name = name;
  18070. range.from = localRange.from;
  18071. range.to = localRange.to;
  18072. serializationRanges.push(range);
  18073. }
  18074. return serializationRanges;
  18075. };
  18076. /**
  18077. * Computes the world matrix of the node
  18078. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18079. * @returns the world matrix
  18080. */
  18081. Node.prototype.computeWorldMatrix = function (force) {
  18082. return BABYLON.Matrix.Identity();
  18083. };
  18084. /**
  18085. * Releases resources associated with this node.
  18086. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18087. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18088. */
  18089. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18090. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18091. if (!doNotRecurse) {
  18092. var nodes = this.getDescendants(true);
  18093. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18094. var node = nodes_1[_i];
  18095. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18096. }
  18097. }
  18098. else {
  18099. var transformNodes = this.getChildTransformNodes(true);
  18100. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18101. var transformNode = transformNodes_1[_a];
  18102. transformNode.parent = null;
  18103. transformNode.computeWorldMatrix(true);
  18104. }
  18105. }
  18106. this.parent = null;
  18107. // Callback
  18108. this.onDisposeObservable.notifyObservers(this);
  18109. this.onDisposeObservable.clear();
  18110. // Behaviors
  18111. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18112. var behavior = _c[_b];
  18113. behavior.detach();
  18114. }
  18115. this._behaviors = [];
  18116. this._isDisposed = true;
  18117. };
  18118. /**
  18119. * Parse animation range data from a serialization object and store them into a given node
  18120. * @param node defines where to store the animation ranges
  18121. * @param parsedNode defines the serialization object to read data from
  18122. * @param scene defines the hosting scene
  18123. */
  18124. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18125. if (parsedNode.ranges) {
  18126. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18127. var data = parsedNode.ranges[index];
  18128. node.createAnimationRange(data.name, data.from, data.to);
  18129. }
  18130. }
  18131. };
  18132. __decorate([
  18133. BABYLON.serialize()
  18134. ], Node.prototype, "name", void 0);
  18135. __decorate([
  18136. BABYLON.serialize()
  18137. ], Node.prototype, "id", void 0);
  18138. __decorate([
  18139. BABYLON.serialize()
  18140. ], Node.prototype, "uniqueId", void 0);
  18141. __decorate([
  18142. BABYLON.serialize()
  18143. ], Node.prototype, "state", void 0);
  18144. __decorate([
  18145. BABYLON.serialize()
  18146. ], Node.prototype, "metadata", void 0);
  18147. return Node;
  18148. }());
  18149. BABYLON.Node = Node;
  18150. })(BABYLON || (BABYLON = {}));
  18151. //# sourceMappingURL=babylon.node.js.map
  18152. var BABYLON;
  18153. (function (BABYLON) {
  18154. var BoundingSphere = /** @class */ (function () {
  18155. /**
  18156. * Creates a new bounding sphere
  18157. * @param min defines the minimum vector (in local space)
  18158. * @param max defines the maximum vector (in local space)
  18159. */
  18160. function BoundingSphere(min, max) {
  18161. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18162. this.reConstruct(min, max);
  18163. }
  18164. /**
  18165. * Recreates the entire bounding sphere from scratch
  18166. * @param min defines the new minimum vector (in local space)
  18167. * @param max defines the new maximum vector (in local space)
  18168. */
  18169. BoundingSphere.prototype.reConstruct = function (min, max) {
  18170. this.minimum = min.clone();
  18171. this.maximum = max.clone();
  18172. var distance = BABYLON.Vector3.Distance(min, max);
  18173. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18174. this.radius = distance * 0.5;
  18175. this.centerWorld = BABYLON.Vector3.Zero();
  18176. this._update(BABYLON.Matrix.Identity());
  18177. };
  18178. // Methods
  18179. BoundingSphere.prototype._update = function (world) {
  18180. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18181. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18182. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18183. };
  18184. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18185. for (var i = 0; i < 6; i++) {
  18186. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18187. return false;
  18188. }
  18189. return true;
  18190. };
  18191. BoundingSphere.prototype.intersectsPoint = function (point) {
  18192. var x = this.centerWorld.x - point.x;
  18193. var y = this.centerWorld.y - point.y;
  18194. var z = this.centerWorld.z - point.z;
  18195. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18196. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18197. return false;
  18198. return true;
  18199. };
  18200. // Statics
  18201. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18202. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18203. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18204. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18205. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18206. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18207. return false;
  18208. return true;
  18209. };
  18210. return BoundingSphere;
  18211. }());
  18212. BABYLON.BoundingSphere = BoundingSphere;
  18213. })(BABYLON || (BABYLON = {}));
  18214. //# sourceMappingURL=babylon.boundingSphere.js.map
  18215. var BABYLON;
  18216. (function (BABYLON) {
  18217. var BoundingBox = /** @class */ (function () {
  18218. /**
  18219. * Creates a new bounding box
  18220. * @param min defines the minimum vector (in local space)
  18221. * @param max defines the maximum vector (in local space)
  18222. */
  18223. function BoundingBox(min, max) {
  18224. this.vectorsWorld = new Array();
  18225. this.reConstruct(min, max);
  18226. }
  18227. // Methods
  18228. /**
  18229. * Recreates the entire bounding box from scratch
  18230. * @param min defines the new minimum vector (in local space)
  18231. * @param max defines the new maximum vector (in local space)
  18232. */
  18233. BoundingBox.prototype.reConstruct = function (min, max) {
  18234. this.minimum = min.clone();
  18235. this.maximum = max.clone();
  18236. // Bounding vectors
  18237. this.vectors = new Array();
  18238. this.vectors.push(this.minimum.clone());
  18239. this.vectors.push(this.maximum.clone());
  18240. this.vectors.push(this.minimum.clone());
  18241. this.vectors[2].x = this.maximum.x;
  18242. this.vectors.push(this.minimum.clone());
  18243. this.vectors[3].y = this.maximum.y;
  18244. this.vectors.push(this.minimum.clone());
  18245. this.vectors[4].z = this.maximum.z;
  18246. this.vectors.push(this.maximum.clone());
  18247. this.vectors[5].z = this.minimum.z;
  18248. this.vectors.push(this.maximum.clone());
  18249. this.vectors[6].x = this.minimum.x;
  18250. this.vectors.push(this.maximum.clone());
  18251. this.vectors[7].y = this.minimum.y;
  18252. // OBB
  18253. this.center = this.maximum.add(this.minimum).scale(0.5);
  18254. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18255. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18256. // World
  18257. for (var index = 0; index < this.vectors.length; index++) {
  18258. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18259. }
  18260. this.minimumWorld = BABYLON.Vector3.Zero();
  18261. this.maximumWorld = BABYLON.Vector3.Zero();
  18262. this.centerWorld = BABYLON.Vector3.Zero();
  18263. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18264. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18265. };
  18266. BoundingBox.prototype.getWorldMatrix = function () {
  18267. return this._worldMatrix;
  18268. };
  18269. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18270. this._worldMatrix.copyFrom(matrix);
  18271. return this;
  18272. };
  18273. BoundingBox.prototype._update = function (world) {
  18274. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18275. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18276. for (var index = 0; index < this.vectors.length; index++) {
  18277. var v = this.vectorsWorld[index];
  18278. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18279. if (v.x < this.minimumWorld.x)
  18280. this.minimumWorld.x = v.x;
  18281. if (v.y < this.minimumWorld.y)
  18282. this.minimumWorld.y = v.y;
  18283. if (v.z < this.minimumWorld.z)
  18284. this.minimumWorld.z = v.z;
  18285. if (v.x > this.maximumWorld.x)
  18286. this.maximumWorld.x = v.x;
  18287. if (v.y > this.maximumWorld.y)
  18288. this.maximumWorld.y = v.y;
  18289. if (v.z > this.maximumWorld.z)
  18290. this.maximumWorld.z = v.z;
  18291. }
  18292. // Extend
  18293. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18294. this.extendSizeWorld.scaleInPlace(0.5);
  18295. // OBB
  18296. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18297. this.centerWorld.scaleInPlace(0.5);
  18298. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18299. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18300. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18301. this._worldMatrix = world;
  18302. };
  18303. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18304. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18305. };
  18306. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18307. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18308. };
  18309. BoundingBox.prototype.intersectsPoint = function (point) {
  18310. var delta = -BABYLON.Epsilon;
  18311. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18312. return false;
  18313. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18314. return false;
  18315. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18316. return false;
  18317. return true;
  18318. };
  18319. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18320. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18321. };
  18322. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18323. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18324. return false;
  18325. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18326. return false;
  18327. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18328. return false;
  18329. return true;
  18330. };
  18331. // Statics
  18332. BoundingBox.Intersects = function (box0, box1) {
  18333. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18334. return false;
  18335. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18336. return false;
  18337. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18338. return false;
  18339. return true;
  18340. };
  18341. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18342. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18343. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18344. return (num <= (sphereRadius * sphereRadius));
  18345. };
  18346. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18347. for (var p = 0; p < 6; p++) {
  18348. for (var i = 0; i < 8; i++) {
  18349. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18350. return false;
  18351. }
  18352. }
  18353. }
  18354. return true;
  18355. };
  18356. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18357. for (var p = 0; p < 6; p++) {
  18358. var inCount = 8;
  18359. for (var i = 0; i < 8; i++) {
  18360. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18361. --inCount;
  18362. }
  18363. else {
  18364. break;
  18365. }
  18366. }
  18367. if (inCount === 0)
  18368. return false;
  18369. }
  18370. return true;
  18371. };
  18372. return BoundingBox;
  18373. }());
  18374. BABYLON.BoundingBox = BoundingBox;
  18375. })(BABYLON || (BABYLON = {}));
  18376. //# sourceMappingURL=babylon.boundingBox.js.map
  18377. var BABYLON;
  18378. (function (BABYLON) {
  18379. var computeBoxExtents = function (axis, box) {
  18380. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18381. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18382. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18383. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18384. var r = r0 + r1 + r2;
  18385. return {
  18386. min: p - r,
  18387. max: p + r
  18388. };
  18389. };
  18390. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18391. var axisOverlap = function (axis, box0, box1) {
  18392. var result0 = computeBoxExtents(axis, box0);
  18393. var result1 = computeBoxExtents(axis, box1);
  18394. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18395. };
  18396. var BoundingInfo = /** @class */ (function () {
  18397. function BoundingInfo(minimum, maximum) {
  18398. this.minimum = minimum;
  18399. this.maximum = maximum;
  18400. this._isLocked = false;
  18401. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18402. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18403. }
  18404. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18405. get: function () {
  18406. return this._isLocked;
  18407. },
  18408. set: function (value) {
  18409. this._isLocked = value;
  18410. },
  18411. enumerable: true,
  18412. configurable: true
  18413. });
  18414. // Methods
  18415. BoundingInfo.prototype.update = function (world) {
  18416. if (this._isLocked) {
  18417. return;
  18418. }
  18419. this.boundingBox._update(world);
  18420. this.boundingSphere._update(world);
  18421. };
  18422. /**
  18423. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18424. * @param center New center of the bounding info
  18425. * @param extend New extend of the bounding info
  18426. */
  18427. BoundingInfo.prototype.centerOn = function (center, extend) {
  18428. this.minimum = center.subtract(extend);
  18429. this.maximum = center.add(extend);
  18430. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18431. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18432. return this;
  18433. };
  18434. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18435. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18436. return false;
  18437. return this.boundingBox.isInFrustum(frustumPlanes);
  18438. };
  18439. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18440. /**
  18441. * Gets the world distance between the min and max points of the bounding box
  18442. */
  18443. get: function () {
  18444. var boundingBox = this.boundingBox;
  18445. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18446. return size.length();
  18447. },
  18448. enumerable: true,
  18449. configurable: true
  18450. });
  18451. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18452. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18453. };
  18454. BoundingInfo.prototype._checkCollision = function (collider) {
  18455. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18456. };
  18457. BoundingInfo.prototype.intersectsPoint = function (point) {
  18458. if (!this.boundingSphere.centerWorld) {
  18459. return false;
  18460. }
  18461. if (!this.boundingSphere.intersectsPoint(point)) {
  18462. return false;
  18463. }
  18464. if (!this.boundingBox.intersectsPoint(point)) {
  18465. return false;
  18466. }
  18467. return true;
  18468. };
  18469. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18470. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18471. return false;
  18472. }
  18473. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18474. return false;
  18475. }
  18476. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18477. return false;
  18478. }
  18479. if (!precise) {
  18480. return true;
  18481. }
  18482. var box0 = this.boundingBox;
  18483. var box1 = boundingInfo.boundingBox;
  18484. if (!axisOverlap(box0.directions[0], box0, box1))
  18485. return false;
  18486. if (!axisOverlap(box0.directions[1], box0, box1))
  18487. return false;
  18488. if (!axisOverlap(box0.directions[2], box0, box1))
  18489. return false;
  18490. if (!axisOverlap(box1.directions[0], box0, box1))
  18491. return false;
  18492. if (!axisOverlap(box1.directions[1], box0, box1))
  18493. return false;
  18494. if (!axisOverlap(box1.directions[2], box0, box1))
  18495. return false;
  18496. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18497. return false;
  18498. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18499. return false;
  18500. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18501. return false;
  18502. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18503. return false;
  18504. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18505. return false;
  18506. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18507. return false;
  18508. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18509. return false;
  18510. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18511. return false;
  18512. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18513. return false;
  18514. return true;
  18515. };
  18516. return BoundingInfo;
  18517. }());
  18518. BABYLON.BoundingInfo = BoundingInfo;
  18519. })(BABYLON || (BABYLON = {}));
  18520. //# sourceMappingURL=babylon.boundingInfo.js.map
  18521. var BABYLON;
  18522. (function (BABYLON) {
  18523. var TransformNode = /** @class */ (function (_super) {
  18524. __extends(TransformNode, _super);
  18525. function TransformNode(name, scene, isPure) {
  18526. if (scene === void 0) { scene = null; }
  18527. if (isPure === void 0) { isPure = true; }
  18528. var _this = _super.call(this, name, scene) || this;
  18529. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18530. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18531. _this._up = new BABYLON.Vector3(0, 1, 0);
  18532. _this._right = new BABYLON.Vector3(1, 0, 0);
  18533. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18534. // Properties
  18535. _this._rotation = BABYLON.Vector3.Zero();
  18536. _this._scaling = BABYLON.Vector3.One();
  18537. _this._isDirty = false;
  18538. /**
  18539. * Set the billboard mode. Default is 0.
  18540. *
  18541. * | Value | Type | Description |
  18542. * | --- | --- | --- |
  18543. * | 0 | BILLBOARDMODE_NONE | |
  18544. * | 1 | BILLBOARDMODE_X | |
  18545. * | 2 | BILLBOARDMODE_Y | |
  18546. * | 4 | BILLBOARDMODE_Z | |
  18547. * | 7 | BILLBOARDMODE_ALL | |
  18548. *
  18549. */
  18550. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18551. _this.scalingDeterminant = 1;
  18552. _this.infiniteDistance = false;
  18553. /**
  18554. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18555. * By default the system will update normals to compensate
  18556. */
  18557. _this.ignoreNonUniformScaling = false;
  18558. _this.position = BABYLON.Vector3.Zero();
  18559. _this._localWorld = BABYLON.Matrix.Zero();
  18560. _this._worldMatrix = BABYLON.Matrix.Zero();
  18561. _this._worldMatrixDeterminant = 0;
  18562. _this._absolutePosition = BABYLON.Vector3.Zero();
  18563. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18564. _this._postMultiplyPivotMatrix = false;
  18565. _this._isWorldMatrixFrozen = false;
  18566. /**
  18567. * An event triggered after the world matrix is updated
  18568. */
  18569. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18570. _this._nonUniformScaling = false;
  18571. if (isPure) {
  18572. _this.getScene().addTransformNode(_this);
  18573. }
  18574. return _this;
  18575. }
  18576. /**
  18577. * Gets a string idenfifying the name of the class
  18578. * @returns "TransformNode" string
  18579. */
  18580. TransformNode.prototype.getClassName = function () {
  18581. return "TransformNode";
  18582. };
  18583. Object.defineProperty(TransformNode.prototype, "rotation", {
  18584. /**
  18585. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18586. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18587. * Default : (0.0, 0.0, 0.0)
  18588. */
  18589. get: function () {
  18590. return this._rotation;
  18591. },
  18592. set: function (newRotation) {
  18593. this._rotation = newRotation;
  18594. },
  18595. enumerable: true,
  18596. configurable: true
  18597. });
  18598. Object.defineProperty(TransformNode.prototype, "scaling", {
  18599. /**
  18600. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18601. * Default : (1.0, 1.0, 1.0)
  18602. */
  18603. get: function () {
  18604. return this._scaling;
  18605. },
  18606. /**
  18607. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18608. * Default : (1.0, 1.0, 1.0)
  18609. */
  18610. set: function (newScaling) {
  18611. this._scaling = newScaling;
  18612. },
  18613. enumerable: true,
  18614. configurable: true
  18615. });
  18616. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18617. /**
  18618. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18619. * It's null by default.
  18620. * 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)
  18621. */
  18622. get: function () {
  18623. return this._rotationQuaternion;
  18624. },
  18625. set: function (quaternion) {
  18626. this._rotationQuaternion = quaternion;
  18627. //reset the rotation vector.
  18628. if (quaternion && this.rotation.length()) {
  18629. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18630. }
  18631. },
  18632. enumerable: true,
  18633. configurable: true
  18634. });
  18635. Object.defineProperty(TransformNode.prototype, "forward", {
  18636. /**
  18637. * The forward direction of that transform in world space.
  18638. */
  18639. get: function () {
  18640. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18641. },
  18642. enumerable: true,
  18643. configurable: true
  18644. });
  18645. Object.defineProperty(TransformNode.prototype, "up", {
  18646. /**
  18647. * The up direction of that transform in world space.
  18648. */
  18649. get: function () {
  18650. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18651. },
  18652. enumerable: true,
  18653. configurable: true
  18654. });
  18655. Object.defineProperty(TransformNode.prototype, "right", {
  18656. /**
  18657. * The right direction of that transform in world space.
  18658. */
  18659. get: function () {
  18660. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18661. },
  18662. enumerable: true,
  18663. configurable: true
  18664. });
  18665. /**
  18666. * Returns the latest update of the World matrix
  18667. * Returns a Matrix.
  18668. */
  18669. TransformNode.prototype.getWorldMatrix = function () {
  18670. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18671. this.computeWorldMatrix();
  18672. }
  18673. return this._worldMatrix;
  18674. };
  18675. /** @hidden */
  18676. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18677. return this._worldMatrixDeterminant;
  18678. };
  18679. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18680. /**
  18681. * Returns directly the latest state of the mesh World matrix.
  18682. * A Matrix is returned.
  18683. */
  18684. get: function () {
  18685. return this._worldMatrix;
  18686. },
  18687. enumerable: true,
  18688. configurable: true
  18689. });
  18690. /**
  18691. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18692. * Returns the TransformNode.
  18693. */
  18694. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18695. this._poseMatrix.copyFrom(matrix);
  18696. return this;
  18697. };
  18698. /**
  18699. * Returns the mesh Pose matrix.
  18700. * Returned object : Matrix
  18701. */
  18702. TransformNode.prototype.getPoseMatrix = function () {
  18703. return this._poseMatrix;
  18704. };
  18705. TransformNode.prototype._isSynchronized = function () {
  18706. if (this._isDirty) {
  18707. return false;
  18708. }
  18709. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18710. return false;
  18711. if (this._cache.pivotMatrixUpdated) {
  18712. return false;
  18713. }
  18714. if (this.infiniteDistance) {
  18715. return false;
  18716. }
  18717. if (!this._cache.position.equals(this.position))
  18718. return false;
  18719. if (this.rotationQuaternion) {
  18720. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18721. return false;
  18722. }
  18723. if (!this._cache.rotation.equals(this.rotation))
  18724. return false;
  18725. if (!this._cache.scaling.equals(this.scaling))
  18726. return false;
  18727. return true;
  18728. };
  18729. TransformNode.prototype._initCache = function () {
  18730. _super.prototype._initCache.call(this);
  18731. this._cache.localMatrixUpdated = false;
  18732. this._cache.position = BABYLON.Vector3.Zero();
  18733. this._cache.scaling = BABYLON.Vector3.Zero();
  18734. this._cache.rotation = BABYLON.Vector3.Zero();
  18735. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18736. this._cache.billboardMode = -1;
  18737. };
  18738. TransformNode.prototype.markAsDirty = function (property) {
  18739. if (property === "rotation") {
  18740. this.rotationQuaternion = null;
  18741. }
  18742. this._currentRenderId = Number.MAX_VALUE;
  18743. this._isDirty = true;
  18744. return this;
  18745. };
  18746. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18747. /**
  18748. * Returns the current mesh absolute position.
  18749. * Retuns a Vector3.
  18750. */
  18751. get: function () {
  18752. return this._absolutePosition;
  18753. },
  18754. enumerable: true,
  18755. configurable: true
  18756. });
  18757. /**
  18758. * Sets a new matrix to apply before all other transformation
  18759. * @param matrix defines the transform matrix
  18760. * @returns the current TransformNode
  18761. */
  18762. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18763. return this.setPivotMatrix(matrix, false);
  18764. };
  18765. /**
  18766. * Sets a new pivot matrix to the current node
  18767. * @param matrix defines the new pivot matrix to use
  18768. * @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
  18769. * @returns the current TransformNode
  18770. */
  18771. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18772. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18773. this._pivotMatrix = matrix.clone();
  18774. this._cache.pivotMatrixUpdated = true;
  18775. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18776. if (this._postMultiplyPivotMatrix) {
  18777. if (!this._pivotMatrixInverse) {
  18778. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18779. }
  18780. else {
  18781. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18782. }
  18783. }
  18784. return this;
  18785. };
  18786. /**
  18787. * Returns the mesh pivot matrix.
  18788. * Default : Identity.
  18789. * A Matrix is returned.
  18790. */
  18791. TransformNode.prototype.getPivotMatrix = function () {
  18792. return this._pivotMatrix;
  18793. };
  18794. /**
  18795. * Prevents the World matrix to be computed any longer.
  18796. * Returns the TransformNode.
  18797. */
  18798. TransformNode.prototype.freezeWorldMatrix = function () {
  18799. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18800. this.computeWorldMatrix(true);
  18801. this._isWorldMatrixFrozen = true;
  18802. return this;
  18803. };
  18804. /**
  18805. * Allows back the World matrix computation.
  18806. * Returns the TransformNode.
  18807. */
  18808. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18809. this._isWorldMatrixFrozen = false;
  18810. this.computeWorldMatrix(true);
  18811. return this;
  18812. };
  18813. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18814. /**
  18815. * True if the World matrix has been frozen.
  18816. * Returns a boolean.
  18817. */
  18818. get: function () {
  18819. return this._isWorldMatrixFrozen;
  18820. },
  18821. enumerable: true,
  18822. configurable: true
  18823. });
  18824. /**
  18825. * Retuns the mesh absolute position in the World.
  18826. * Returns a Vector3.
  18827. */
  18828. TransformNode.prototype.getAbsolutePosition = function () {
  18829. this.computeWorldMatrix();
  18830. return this._absolutePosition;
  18831. };
  18832. /**
  18833. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18834. * Returns the TransformNode.
  18835. */
  18836. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18837. if (!absolutePosition) {
  18838. return this;
  18839. }
  18840. var absolutePositionX;
  18841. var absolutePositionY;
  18842. var absolutePositionZ;
  18843. if (absolutePosition.x === undefined) {
  18844. if (arguments.length < 3) {
  18845. return this;
  18846. }
  18847. absolutePositionX = arguments[0];
  18848. absolutePositionY = arguments[1];
  18849. absolutePositionZ = arguments[2];
  18850. }
  18851. else {
  18852. absolutePositionX = absolutePosition.x;
  18853. absolutePositionY = absolutePosition.y;
  18854. absolutePositionZ = absolutePosition.z;
  18855. }
  18856. if (this.parent) {
  18857. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18858. invertParentWorldMatrix.invert();
  18859. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18860. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18861. }
  18862. else {
  18863. this.position.x = absolutePositionX;
  18864. this.position.y = absolutePositionY;
  18865. this.position.z = absolutePositionZ;
  18866. }
  18867. return this;
  18868. };
  18869. /**
  18870. * Sets the mesh position in its local space.
  18871. * Returns the TransformNode.
  18872. */
  18873. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18874. this.computeWorldMatrix();
  18875. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18876. return this;
  18877. };
  18878. /**
  18879. * Returns the mesh position in the local space from the current World matrix values.
  18880. * Returns a new Vector3.
  18881. */
  18882. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18883. this.computeWorldMatrix();
  18884. var invLocalWorldMatrix = this._localWorld.clone();
  18885. invLocalWorldMatrix.invert();
  18886. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18887. };
  18888. /**
  18889. * Translates the mesh along the passed Vector3 in its local space.
  18890. * Returns the TransformNode.
  18891. */
  18892. TransformNode.prototype.locallyTranslate = function (vector3) {
  18893. this.computeWorldMatrix(true);
  18894. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18895. return this;
  18896. };
  18897. /**
  18898. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18899. * @param targetPoint the position (must be in same space as current mesh) to look at
  18900. * @param yawCor optional yaw (y-axis) correction in radians
  18901. * @param pitchCor optional pitch (x-axis) correction in radians
  18902. * @param rollCor optional roll (z-axis) correction in radians
  18903. * @param space the choosen space of the target
  18904. * @returns the TransformNode.
  18905. */
  18906. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18907. if (yawCor === void 0) { yawCor = 0; }
  18908. if (pitchCor === void 0) { pitchCor = 0; }
  18909. if (rollCor === void 0) { rollCor = 0; }
  18910. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18911. var dv = TransformNode._lookAtVectorCache;
  18912. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18913. targetPoint.subtractToRef(pos, dv);
  18914. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18915. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18916. var pitch = Math.atan2(dv.y, len);
  18917. if (this.rotationQuaternion) {
  18918. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18919. }
  18920. else {
  18921. this.rotation.x = pitch + pitchCor;
  18922. this.rotation.y = yaw + yawCor;
  18923. this.rotation.z = rollCor;
  18924. }
  18925. return this;
  18926. };
  18927. /**
  18928. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18929. * This Vector3 is expressed in the World space.
  18930. */
  18931. TransformNode.prototype.getDirection = function (localAxis) {
  18932. var result = BABYLON.Vector3.Zero();
  18933. this.getDirectionToRef(localAxis, result);
  18934. return result;
  18935. };
  18936. /**
  18937. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18938. * localAxis is expressed in the mesh local space.
  18939. * result is computed in the Wordl space from the mesh World matrix.
  18940. * Returns the TransformNode.
  18941. */
  18942. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18943. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18944. return this;
  18945. };
  18946. /**
  18947. * Sets a new pivot point to the current node
  18948. * @param point defines the new pivot point to use
  18949. * @param space defines if the point is in world or local space (local by default)
  18950. * @returns the current TransformNode
  18951. */
  18952. TransformNode.prototype.setPivotPoint = function (point, space) {
  18953. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18954. if (this.getScene().getRenderId() == 0) {
  18955. this.computeWorldMatrix(true);
  18956. }
  18957. var wm = this.getWorldMatrix();
  18958. if (space == BABYLON.Space.WORLD) {
  18959. var tmat = BABYLON.Tmp.Matrix[0];
  18960. wm.invertToRef(tmat);
  18961. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18962. }
  18963. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18964. };
  18965. /**
  18966. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18967. */
  18968. TransformNode.prototype.getPivotPoint = function () {
  18969. var point = BABYLON.Vector3.Zero();
  18970. this.getPivotPointToRef(point);
  18971. return point;
  18972. };
  18973. /**
  18974. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18975. * Returns the TransformNode.
  18976. */
  18977. TransformNode.prototype.getPivotPointToRef = function (result) {
  18978. result.x = -this._pivotMatrix.m[12];
  18979. result.y = -this._pivotMatrix.m[13];
  18980. result.z = -this._pivotMatrix.m[14];
  18981. return this;
  18982. };
  18983. /**
  18984. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18985. */
  18986. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18987. var point = BABYLON.Vector3.Zero();
  18988. this.getAbsolutePivotPointToRef(point);
  18989. return point;
  18990. };
  18991. /**
  18992. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18993. * Returns the TransformNode.
  18994. */
  18995. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18996. result.x = this._pivotMatrix.m[12];
  18997. result.y = this._pivotMatrix.m[13];
  18998. result.z = this._pivotMatrix.m[14];
  18999. this.getPivotPointToRef(result);
  19000. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19001. return this;
  19002. };
  19003. /**
  19004. * Defines the passed node as the parent of the current node.
  19005. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19006. * Returns the TransformNode.
  19007. */
  19008. TransformNode.prototype.setParent = function (node) {
  19009. if (node === null && this.parent === null) {
  19010. return this;
  19011. }
  19012. if (node === null) {
  19013. var rotation = BABYLON.Tmp.Quaternion[0];
  19014. var position = BABYLON.Tmp.Vector3[0];
  19015. var scale = BABYLON.Tmp.Vector3[1];
  19016. if (this.parent && this.parent.computeWorldMatrix) {
  19017. this.parent.computeWorldMatrix(true);
  19018. }
  19019. this.computeWorldMatrix(true);
  19020. this.getWorldMatrix().decompose(scale, rotation, position);
  19021. if (this.rotationQuaternion) {
  19022. this.rotationQuaternion.copyFrom(rotation);
  19023. }
  19024. else {
  19025. rotation.toEulerAnglesToRef(this.rotation);
  19026. }
  19027. this.scaling.x = scale.x;
  19028. this.scaling.y = scale.y;
  19029. this.scaling.z = scale.z;
  19030. this.position.x = position.x;
  19031. this.position.y = position.y;
  19032. this.position.z = position.z;
  19033. }
  19034. else {
  19035. var rotation = BABYLON.Tmp.Quaternion[0];
  19036. var position = BABYLON.Tmp.Vector3[0];
  19037. var scale = BABYLON.Tmp.Vector3[1];
  19038. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19039. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19040. this.computeWorldMatrix(true);
  19041. node.computeWorldMatrix(true);
  19042. node.getWorldMatrix().invertToRef(invParentMatrix);
  19043. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19044. diffMatrix.decompose(scale, rotation, position);
  19045. if (this.rotationQuaternion) {
  19046. this.rotationQuaternion.copyFrom(rotation);
  19047. }
  19048. else {
  19049. rotation.toEulerAnglesToRef(this.rotation);
  19050. }
  19051. this.position.x = position.x;
  19052. this.position.y = position.y;
  19053. this.position.z = position.z;
  19054. this.scaling.x = scale.x;
  19055. this.scaling.y = scale.y;
  19056. this.scaling.z = scale.z;
  19057. }
  19058. this.parent = node;
  19059. return this;
  19060. };
  19061. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19062. get: function () {
  19063. return this._nonUniformScaling;
  19064. },
  19065. enumerable: true,
  19066. configurable: true
  19067. });
  19068. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19069. if (this._nonUniformScaling === value) {
  19070. return false;
  19071. }
  19072. this._nonUniformScaling = value;
  19073. return true;
  19074. };
  19075. /**
  19076. * Attach the current TransformNode to another TransformNode associated with a bone
  19077. * @param bone Bone affecting the TransformNode
  19078. * @param affectedTransformNode TransformNode associated with the bone
  19079. */
  19080. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19081. this._transformToBoneReferal = affectedTransformNode;
  19082. this.parent = bone;
  19083. if (bone.getWorldMatrix().determinant() < 0) {
  19084. this.scalingDeterminant *= -1;
  19085. }
  19086. return this;
  19087. };
  19088. TransformNode.prototype.detachFromBone = function () {
  19089. if (!this.parent) {
  19090. return this;
  19091. }
  19092. if (this.parent.getWorldMatrix().determinant() < 0) {
  19093. this.scalingDeterminant *= -1;
  19094. }
  19095. this._transformToBoneReferal = null;
  19096. this.parent = null;
  19097. return this;
  19098. };
  19099. /**
  19100. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19101. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19102. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19103. * The passed axis is also normalized.
  19104. * Returns the TransformNode.
  19105. */
  19106. TransformNode.prototype.rotate = function (axis, amount, space) {
  19107. axis.normalize();
  19108. if (!this.rotationQuaternion) {
  19109. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19110. this.rotation = BABYLON.Vector3.Zero();
  19111. }
  19112. var rotationQuaternion;
  19113. if (!space || space === BABYLON.Space.LOCAL) {
  19114. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19115. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19116. }
  19117. else {
  19118. if (this.parent) {
  19119. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19120. invertParentWorldMatrix.invert();
  19121. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19122. }
  19123. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19124. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19125. }
  19126. return this;
  19127. };
  19128. /**
  19129. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19130. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19131. * The passed axis is also normalized.
  19132. * Returns the TransformNode.
  19133. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19134. */
  19135. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19136. axis.normalize();
  19137. if (!this.rotationQuaternion) {
  19138. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19139. this.rotation.copyFromFloats(0, 0, 0);
  19140. }
  19141. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19142. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19143. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19144. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19145. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19146. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19147. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19148. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19149. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19150. return this;
  19151. };
  19152. /**
  19153. * Translates the mesh along the axis vector for the passed distance in the given space.
  19154. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19155. * Returns the TransformNode.
  19156. */
  19157. TransformNode.prototype.translate = function (axis, distance, space) {
  19158. var displacementVector = axis.scale(distance);
  19159. if (!space || space === BABYLON.Space.LOCAL) {
  19160. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19161. this.setPositionWithLocalVector(tempV3);
  19162. }
  19163. else {
  19164. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19165. }
  19166. return this;
  19167. };
  19168. /**
  19169. * Adds a rotation step to the mesh current rotation.
  19170. * x, y, z are Euler angles expressed in radians.
  19171. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19172. * This means this rotation is made in the mesh local space only.
  19173. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19174. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19175. * ```javascript
  19176. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19177. * ```
  19178. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19179. * 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.
  19180. * Returns the TransformNode.
  19181. */
  19182. TransformNode.prototype.addRotation = function (x, y, z) {
  19183. var rotationQuaternion;
  19184. if (this.rotationQuaternion) {
  19185. rotationQuaternion = this.rotationQuaternion;
  19186. }
  19187. else {
  19188. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19189. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19190. }
  19191. var accumulation = BABYLON.Tmp.Quaternion[0];
  19192. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19193. rotationQuaternion.multiplyInPlace(accumulation);
  19194. if (!this.rotationQuaternion) {
  19195. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19196. }
  19197. return this;
  19198. };
  19199. /**
  19200. * Computes the mesh World matrix and returns it.
  19201. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19202. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19203. * If the parameter `force`is set to `true`, the actual computation is done.
  19204. * Returns the mesh World Matrix.
  19205. */
  19206. TransformNode.prototype.computeWorldMatrix = function (force) {
  19207. if (this._isWorldMatrixFrozen) {
  19208. return this._worldMatrix;
  19209. }
  19210. if (!force && this.isSynchronized(true)) {
  19211. this._currentRenderId = this.getScene().getRenderId();
  19212. return this._worldMatrix;
  19213. }
  19214. this._cache.position.copyFrom(this.position);
  19215. this._cache.scaling.copyFrom(this.scaling);
  19216. this._cache.pivotMatrixUpdated = false;
  19217. this._cache.billboardMode = this.billboardMode;
  19218. this._currentRenderId = this.getScene().getRenderId();
  19219. this._childRenderId = this.getScene().getRenderId();
  19220. this._isDirty = false;
  19221. // Scaling
  19222. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19223. // Rotation
  19224. //rotate, if quaternion is set and rotation was used
  19225. if (this.rotationQuaternion) {
  19226. var len = this.rotation.length();
  19227. if (len) {
  19228. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19229. this.rotation.copyFromFloats(0, 0, 0);
  19230. }
  19231. }
  19232. if (this.rotationQuaternion) {
  19233. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19234. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19235. }
  19236. else {
  19237. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19238. this._cache.rotation.copyFrom(this.rotation);
  19239. }
  19240. // Translation
  19241. var camera = this.getScene().activeCamera;
  19242. if (this.infiniteDistance && !this.parent && camera) {
  19243. var cameraWorldMatrix = camera.getWorldMatrix();
  19244. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19245. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19246. }
  19247. else {
  19248. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19249. }
  19250. // Composing transformations
  19251. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19252. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19253. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19254. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19255. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19256. // Need to decompose each rotation here
  19257. var currentPosition = BABYLON.Tmp.Vector3[3];
  19258. if (this.parent && this.parent.getWorldMatrix) {
  19259. if (this._transformToBoneReferal) {
  19260. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19261. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19262. }
  19263. else {
  19264. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19265. }
  19266. }
  19267. else {
  19268. currentPosition.copyFrom(this.position);
  19269. }
  19270. currentPosition.subtractInPlace(camera.globalPosition);
  19271. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19272. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19273. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19274. }
  19275. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19276. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19277. }
  19278. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19279. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19280. }
  19281. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19282. }
  19283. else {
  19284. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19285. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19286. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19287. }
  19288. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19289. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19290. }
  19291. // Local world
  19292. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19293. // Parent
  19294. if (this.parent && this.parent.getWorldMatrix) {
  19295. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19296. if (this._transformToBoneReferal) {
  19297. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19298. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19299. }
  19300. else {
  19301. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19302. }
  19303. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19304. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19305. this._worldMatrix.copyFrom(this._localWorld);
  19306. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19307. }
  19308. else {
  19309. if (this._transformToBoneReferal) {
  19310. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19311. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19312. }
  19313. else {
  19314. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19315. }
  19316. }
  19317. this._markSyncedWithParent();
  19318. }
  19319. else {
  19320. this._worldMatrix.copyFrom(this._localWorld);
  19321. }
  19322. // Post multiply inverse of pivotMatrix
  19323. if (this._postMultiplyPivotMatrix) {
  19324. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19325. }
  19326. // Normal matrix
  19327. if (!this.ignoreNonUniformScaling) {
  19328. if (this.scaling.isNonUniform) {
  19329. this._updateNonUniformScalingState(true);
  19330. }
  19331. else if (this.parent && this.parent._nonUniformScaling) {
  19332. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19333. }
  19334. else {
  19335. this._updateNonUniformScalingState(false);
  19336. }
  19337. }
  19338. else {
  19339. this._updateNonUniformScalingState(false);
  19340. }
  19341. this._afterComputeWorldMatrix();
  19342. // Absolute position
  19343. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19344. // Callbacks
  19345. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19346. if (!this._poseMatrix) {
  19347. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19348. }
  19349. // Cache the determinant
  19350. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19351. return this._worldMatrix;
  19352. };
  19353. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19354. };
  19355. /**
  19356. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19357. * @param func: callback function to add
  19358. *
  19359. * Returns the TransformNode.
  19360. */
  19361. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19362. this.onAfterWorldMatrixUpdateObservable.add(func);
  19363. return this;
  19364. };
  19365. /**
  19366. * Removes a registered callback function.
  19367. * Returns the TransformNode.
  19368. */
  19369. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19370. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19371. return this;
  19372. };
  19373. /**
  19374. * Clone the current transform node
  19375. * Returns the new transform node
  19376. * @param name Name of the new clone
  19377. * @param newParent New parent for the clone
  19378. * @param doNotCloneChildren Do not clone children hierarchy
  19379. */
  19380. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19381. var _this = this;
  19382. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19383. result.name = name;
  19384. result.id = name;
  19385. if (newParent) {
  19386. result.parent = newParent;
  19387. }
  19388. if (!doNotCloneChildren) {
  19389. // Children
  19390. var directDescendants = this.getDescendants(true);
  19391. for (var index = 0; index < directDescendants.length; index++) {
  19392. var child = directDescendants[index];
  19393. if (child.clone) {
  19394. child.clone(name + "." + child.name, result);
  19395. }
  19396. }
  19397. }
  19398. return result;
  19399. };
  19400. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19401. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19402. serializationObject.type = this.getClassName();
  19403. // Parent
  19404. if (this.parent) {
  19405. serializationObject.parentId = this.parent.id;
  19406. }
  19407. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19408. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19409. }
  19410. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19411. serializationObject.isEnabled = this.isEnabled();
  19412. // Parent
  19413. if (this.parent) {
  19414. serializationObject.parentId = this.parent.id;
  19415. }
  19416. return serializationObject;
  19417. };
  19418. // Statics
  19419. /**
  19420. * Returns a new TransformNode object parsed from the source provided.
  19421. * The parameter `parsedMesh` is the source.
  19422. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19423. */
  19424. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19425. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19426. if (BABYLON.Tags) {
  19427. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19428. }
  19429. if (parsedTransformNode.localMatrix) {
  19430. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19431. }
  19432. else if (parsedTransformNode.pivotMatrix) {
  19433. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19434. }
  19435. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19436. // Parent
  19437. if (parsedTransformNode.parentId) {
  19438. transformNode._waitingParentId = parsedTransformNode.parentId;
  19439. }
  19440. return transformNode;
  19441. };
  19442. /**
  19443. * Releases resources associated with this transform node.
  19444. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19445. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19446. */
  19447. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19448. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19449. // Animations
  19450. this.getScene().stopAnimation(this);
  19451. // Remove from scene
  19452. this.getScene().removeTransformNode(this);
  19453. this.onAfterWorldMatrixUpdateObservable.clear();
  19454. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19455. };
  19456. // Statics
  19457. TransformNode.BILLBOARDMODE_NONE = 0;
  19458. TransformNode.BILLBOARDMODE_X = 1;
  19459. TransformNode.BILLBOARDMODE_Y = 2;
  19460. TransformNode.BILLBOARDMODE_Z = 4;
  19461. TransformNode.BILLBOARDMODE_ALL = 7;
  19462. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19463. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19464. __decorate([
  19465. BABYLON.serializeAsVector3()
  19466. ], TransformNode.prototype, "_rotation", void 0);
  19467. __decorate([
  19468. BABYLON.serializeAsQuaternion()
  19469. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19470. __decorate([
  19471. BABYLON.serializeAsVector3()
  19472. ], TransformNode.prototype, "_scaling", void 0);
  19473. __decorate([
  19474. BABYLON.serialize()
  19475. ], TransformNode.prototype, "billboardMode", void 0);
  19476. __decorate([
  19477. BABYLON.serialize()
  19478. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19479. __decorate([
  19480. BABYLON.serialize()
  19481. ], TransformNode.prototype, "infiniteDistance", void 0);
  19482. __decorate([
  19483. BABYLON.serialize()
  19484. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19485. __decorate([
  19486. BABYLON.serializeAsVector3()
  19487. ], TransformNode.prototype, "position", void 0);
  19488. return TransformNode;
  19489. }(BABYLON.Node));
  19490. BABYLON.TransformNode = TransformNode;
  19491. })(BABYLON || (BABYLON = {}));
  19492. //# sourceMappingURL=babylon.transformNode.js.map
  19493. var BABYLON;
  19494. (function (BABYLON) {
  19495. /**
  19496. * Class used to store all common mesh properties
  19497. */
  19498. var AbstractMesh = /** @class */ (function (_super) {
  19499. __extends(AbstractMesh, _super);
  19500. // Constructor
  19501. /**
  19502. * Creates a new AbstractMesh
  19503. * @param name defines the name of the mesh
  19504. * @param scene defines the hosting scene
  19505. */
  19506. function AbstractMesh(name, scene) {
  19507. if (scene === void 0) { scene = null; }
  19508. var _this = _super.call(this, name, scene, false) || this;
  19509. _this._facetNb = 0; // facet number
  19510. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19511. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19512. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19513. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19514. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19515. _this._subDiv = {
  19516. max: 1,
  19517. X: 1,
  19518. Y: 1,
  19519. Z: 1
  19520. };
  19521. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19522. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19523. // Events
  19524. /**
  19525. * An event triggered when this mesh collides with another one
  19526. */
  19527. _this.onCollideObservable = new BABYLON.Observable();
  19528. /**
  19529. * An event triggered when the collision's position changes
  19530. */
  19531. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19532. /**
  19533. * An event triggered when material is changed
  19534. */
  19535. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19536. // Properties
  19537. /**
  19538. * Gets or sets the orientation for POV movement & rotation
  19539. */
  19540. _this.definedFacingForward = true;
  19541. /**
  19542. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19543. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19544. * * 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.
  19545. * @see http://doc.babylonjs.com/features/occlusionquery
  19546. */
  19547. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19548. /**
  19549. * 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:
  19550. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19551. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19552. * * 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.
  19553. * @see http://doc.babylonjs.com/features/occlusionquery
  19554. */
  19555. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19556. /**
  19557. * 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.
  19558. * The default value is -1 which means don't break the query and wait till the result
  19559. * @see http://doc.babylonjs.com/features/occlusionquery
  19560. */
  19561. _this.occlusionRetryCount = -1;
  19562. _this._occlusionInternalRetryCounter = 0;
  19563. _this._isOccluded = false;
  19564. _this._isOcclusionQueryInProgress = false;
  19565. _this._visibility = 1.0;
  19566. /** Gets or sets the alpha index used to sort transparent meshes
  19567. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19568. */
  19569. _this.alphaIndex = Number.MAX_VALUE;
  19570. /**
  19571. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19572. */
  19573. _this.isVisible = true;
  19574. /**
  19575. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19576. */
  19577. _this.isPickable = true;
  19578. /**
  19579. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19580. */
  19581. _this.showBoundingBox = false;
  19582. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19583. _this.showSubMeshesBoundingBox = false;
  19584. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19585. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19586. */
  19587. _this.isBlocker = false;
  19588. /**
  19589. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19590. */
  19591. _this.enablePointerMoveEvents = false;
  19592. /**
  19593. * Specifies the rendering group id for this mesh (0 by default)
  19594. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19595. */
  19596. _this.renderingGroupId = 0;
  19597. _this._receiveShadows = false;
  19598. /**
  19599. * Gets or sets a boolean indicating if the outline must be rendered as well
  19600. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19601. */
  19602. _this.renderOutline = false;
  19603. /** Defines color to use when rendering outline */
  19604. _this.outlineColor = BABYLON.Color3.Red();
  19605. /** Define width to use when rendering outline */
  19606. _this.outlineWidth = 0.02;
  19607. /**
  19608. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19609. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19610. */
  19611. _this.renderOverlay = false;
  19612. /** Defines color to use when rendering overlay */
  19613. _this.overlayColor = BABYLON.Color3.Red();
  19614. /** Defines alpha to use when rendering overlay */
  19615. _this.overlayAlpha = 0.5;
  19616. _this._hasVertexAlpha = false;
  19617. _this._useVertexColors = true;
  19618. _this._computeBonesUsingShaders = true;
  19619. _this._numBoneInfluencers = 4;
  19620. _this._applyFog = true;
  19621. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19622. _this.useOctreeForRenderingSelection = true;
  19623. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19624. _this.useOctreeForPicking = true;
  19625. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19626. _this.useOctreeForCollisions = true;
  19627. _this._layerMask = 0x0FFFFFFF;
  19628. /**
  19629. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19630. */
  19631. _this.alwaysSelectAsActiveMesh = false;
  19632. /**
  19633. * Gets or sets the current action manager
  19634. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19635. */
  19636. _this.actionManager = null;
  19637. /**
  19638. * Gets or sets impostor used for physic simulation
  19639. * @see http://doc.babylonjs.com/features/physics_engine
  19640. */
  19641. _this.physicsImpostor = null;
  19642. // Collisions
  19643. _this._checkCollisions = false;
  19644. _this._collisionMask = -1;
  19645. _this._collisionGroup = -1;
  19646. /**
  19647. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19648. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19649. */
  19650. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19651. /**
  19652. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19653. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19654. */
  19655. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19656. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19657. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19658. // Edges
  19659. /**
  19660. * Defines edge width used when edgesRenderer is enabled
  19661. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19662. */
  19663. _this.edgesWidth = 1;
  19664. /**
  19665. * Defines edge color used when edgesRenderer is enabled
  19666. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19667. */
  19668. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19669. // Cache
  19670. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19671. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19672. /** @hidden */
  19673. _this._renderId = 0;
  19674. /** @hidden */
  19675. _this._intersectionsInProgress = new Array();
  19676. /** @hidden */
  19677. _this._unIndexed = false;
  19678. /** @hidden */
  19679. _this._lightSources = new Array();
  19680. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19681. if (collidedMesh === void 0) { collidedMesh = null; }
  19682. //TODO move this to the collision coordinator!
  19683. if (_this.getScene().workerCollisions)
  19684. newPosition.multiplyInPlace(_this._collider._radius);
  19685. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19686. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19687. _this.position.addInPlace(_this._diffPositionForCollisions);
  19688. }
  19689. if (collidedMesh) {
  19690. _this.onCollideObservable.notifyObservers(collidedMesh);
  19691. }
  19692. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19693. };
  19694. _this.getScene().addMesh(_this);
  19695. _this._resyncLightSources();
  19696. return _this;
  19697. }
  19698. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19699. /**
  19700. * No billboard
  19701. */
  19702. get: function () {
  19703. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19704. },
  19705. enumerable: true,
  19706. configurable: true
  19707. });
  19708. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19709. /** Billboard on X axis */
  19710. get: function () {
  19711. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19712. },
  19713. enumerable: true,
  19714. configurable: true
  19715. });
  19716. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19717. /** Billboard on Y axis */
  19718. get: function () {
  19719. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19720. },
  19721. enumerable: true,
  19722. configurable: true
  19723. });
  19724. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19725. /** Billboard on Z axis */
  19726. get: function () {
  19727. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19728. },
  19729. enumerable: true,
  19730. configurable: true
  19731. });
  19732. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19733. /** Billboard on all axes */
  19734. get: function () {
  19735. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19736. },
  19737. enumerable: true,
  19738. configurable: true
  19739. });
  19740. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19741. /**
  19742. * Gets the number of facets in the mesh
  19743. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19744. */
  19745. get: function () {
  19746. return this._facetNb;
  19747. },
  19748. enumerable: true,
  19749. configurable: true
  19750. });
  19751. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19752. /**
  19753. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19754. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19755. */
  19756. get: function () {
  19757. return this._partitioningSubdivisions;
  19758. },
  19759. set: function (nb) {
  19760. this._partitioningSubdivisions = nb;
  19761. },
  19762. enumerable: true,
  19763. configurable: true
  19764. });
  19765. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19766. /**
  19767. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19768. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19769. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19770. */
  19771. get: function () {
  19772. return this._partitioningBBoxRatio;
  19773. },
  19774. set: function (ratio) {
  19775. this._partitioningBBoxRatio = ratio;
  19776. },
  19777. enumerable: true,
  19778. configurable: true
  19779. });
  19780. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19781. /**
  19782. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19783. * Works only for updatable meshes.
  19784. * Doesn't work with multi-materials
  19785. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19786. */
  19787. get: function () {
  19788. return this._facetDepthSort;
  19789. },
  19790. set: function (sort) {
  19791. this._facetDepthSort = sort;
  19792. },
  19793. enumerable: true,
  19794. configurable: true
  19795. });
  19796. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19797. /**
  19798. * The location (Vector3) where the facet depth sort must be computed from.
  19799. * By default, the active camera position.
  19800. * Used only when facet depth sort is enabled
  19801. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19802. */
  19803. get: function () {
  19804. return this._facetDepthSortFrom;
  19805. },
  19806. set: function (location) {
  19807. this._facetDepthSortFrom = location;
  19808. },
  19809. enumerable: true,
  19810. configurable: true
  19811. });
  19812. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19813. /**
  19814. * gets a boolean indicating if facetData is enabled
  19815. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19816. */
  19817. get: function () {
  19818. return this._facetDataEnabled;
  19819. },
  19820. enumerable: true,
  19821. configurable: true
  19822. });
  19823. /** @hidden */
  19824. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19825. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19826. return false;
  19827. }
  19828. this._markSubMeshesAsMiscDirty();
  19829. return true;
  19830. };
  19831. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19832. /** Set a function to call when this mesh collides with another one */
  19833. set: function (callback) {
  19834. if (this._onCollideObserver) {
  19835. this.onCollideObservable.remove(this._onCollideObserver);
  19836. }
  19837. this._onCollideObserver = this.onCollideObservable.add(callback);
  19838. },
  19839. enumerable: true,
  19840. configurable: true
  19841. });
  19842. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19843. /** Set a function to call when the collision's position changes */
  19844. set: function (callback) {
  19845. if (this._onCollisionPositionChangeObserver) {
  19846. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19847. }
  19848. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19849. },
  19850. enumerable: true,
  19851. configurable: true
  19852. });
  19853. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19854. /**
  19855. * 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
  19856. * @see http://doc.babylonjs.com/features/occlusionquery
  19857. */
  19858. get: function () {
  19859. return this._isOccluded;
  19860. },
  19861. set: function (value) {
  19862. this._isOccluded = value;
  19863. },
  19864. enumerable: true,
  19865. configurable: true
  19866. });
  19867. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19868. /**
  19869. * Flag to check the progress status of the query
  19870. * @see http://doc.babylonjs.com/features/occlusionquery
  19871. */
  19872. get: function () {
  19873. return this._isOcclusionQueryInProgress;
  19874. },
  19875. enumerable: true,
  19876. configurable: true
  19877. });
  19878. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19879. /**
  19880. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19881. */
  19882. get: function () {
  19883. return this._visibility;
  19884. },
  19885. /**
  19886. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19887. */
  19888. set: function (value) {
  19889. if (this._visibility === value) {
  19890. return;
  19891. }
  19892. this._visibility = value;
  19893. this._markSubMeshesAsMiscDirty();
  19894. },
  19895. enumerable: true,
  19896. configurable: true
  19897. });
  19898. Object.defineProperty(AbstractMesh.prototype, "material", {
  19899. /** Gets or sets current material */
  19900. get: function () {
  19901. return this._material;
  19902. },
  19903. set: function (value) {
  19904. if (this._material === value) {
  19905. return;
  19906. }
  19907. this._material = value;
  19908. if (this.onMaterialChangedObservable.hasObservers) {
  19909. this.onMaterialChangedObservable.notifyObservers(this);
  19910. }
  19911. if (!this.subMeshes) {
  19912. return;
  19913. }
  19914. this._unBindEffect();
  19915. },
  19916. enumerable: true,
  19917. configurable: true
  19918. });
  19919. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19920. /**
  19921. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19922. * @see http://doc.babylonjs.com/babylon101/shadows
  19923. */
  19924. get: function () {
  19925. return this._receiveShadows;
  19926. },
  19927. set: function (value) {
  19928. if (this._receiveShadows === value) {
  19929. return;
  19930. }
  19931. this._receiveShadows = value;
  19932. this._markSubMeshesAsLightDirty();
  19933. },
  19934. enumerable: true,
  19935. configurable: true
  19936. });
  19937. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19938. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19939. get: function () {
  19940. return this._hasVertexAlpha;
  19941. },
  19942. set: function (value) {
  19943. if (this._hasVertexAlpha === value) {
  19944. return;
  19945. }
  19946. this._hasVertexAlpha = value;
  19947. this._markSubMeshesAsAttributesDirty();
  19948. this._markSubMeshesAsMiscDirty();
  19949. },
  19950. enumerable: true,
  19951. configurable: true
  19952. });
  19953. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19954. /** 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) */
  19955. get: function () {
  19956. return this._useVertexColors;
  19957. },
  19958. set: function (value) {
  19959. if (this._useVertexColors === value) {
  19960. return;
  19961. }
  19962. this._useVertexColors = value;
  19963. this._markSubMeshesAsAttributesDirty();
  19964. },
  19965. enumerable: true,
  19966. configurable: true
  19967. });
  19968. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19969. /**
  19970. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19971. */
  19972. get: function () {
  19973. return this._computeBonesUsingShaders;
  19974. },
  19975. set: function (value) {
  19976. if (this._computeBonesUsingShaders === value) {
  19977. return;
  19978. }
  19979. this._computeBonesUsingShaders = value;
  19980. this._markSubMeshesAsAttributesDirty();
  19981. },
  19982. enumerable: true,
  19983. configurable: true
  19984. });
  19985. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19986. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19987. get: function () {
  19988. return this._numBoneInfluencers;
  19989. },
  19990. set: function (value) {
  19991. if (this._numBoneInfluencers === value) {
  19992. return;
  19993. }
  19994. this._numBoneInfluencers = value;
  19995. this._markSubMeshesAsAttributesDirty();
  19996. },
  19997. enumerable: true,
  19998. configurable: true
  19999. });
  20000. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20001. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20002. get: function () {
  20003. return this._applyFog;
  20004. },
  20005. set: function (value) {
  20006. if (this._applyFog === value) {
  20007. return;
  20008. }
  20009. this._applyFog = value;
  20010. this._markSubMeshesAsMiscDirty();
  20011. },
  20012. enumerable: true,
  20013. configurable: true
  20014. });
  20015. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20016. /**
  20017. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20018. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20019. */
  20020. get: function () {
  20021. return this._layerMask;
  20022. },
  20023. set: function (value) {
  20024. if (value === this._layerMask) {
  20025. return;
  20026. }
  20027. this._layerMask = value;
  20028. this._resyncLightSources();
  20029. },
  20030. enumerable: true,
  20031. configurable: true
  20032. });
  20033. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20034. /**
  20035. * Gets or sets a collision mask used to mask collisions (default is -1).
  20036. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20037. */
  20038. get: function () {
  20039. return this._collisionMask;
  20040. },
  20041. set: function (mask) {
  20042. this._collisionMask = !isNaN(mask) ? mask : -1;
  20043. },
  20044. enumerable: true,
  20045. configurable: true
  20046. });
  20047. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20048. /**
  20049. * Gets or sets the current collision group mask (-1 by default).
  20050. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20051. */
  20052. get: function () {
  20053. return this._collisionGroup;
  20054. },
  20055. set: function (mask) {
  20056. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20057. },
  20058. enumerable: true,
  20059. configurable: true
  20060. });
  20061. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20062. /** @hidden */
  20063. get: function () {
  20064. return null;
  20065. },
  20066. enumerable: true,
  20067. configurable: true
  20068. });
  20069. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20070. get: function () {
  20071. return this._skeleton;
  20072. },
  20073. /**
  20074. * Gets or sets a skeleton to apply skining transformations
  20075. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20076. */
  20077. set: function (value) {
  20078. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20079. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20080. }
  20081. if (value && value.needInitialSkinMatrix) {
  20082. value._registerMeshWithPoseMatrix(this);
  20083. }
  20084. this._skeleton = value;
  20085. if (!this._skeleton) {
  20086. this._bonesTransformMatrices = null;
  20087. }
  20088. this._markSubMeshesAsAttributesDirty();
  20089. },
  20090. enumerable: true,
  20091. configurable: true
  20092. });
  20093. /**
  20094. * Returns the string "AbstractMesh"
  20095. * @returns "AbstractMesh"
  20096. */
  20097. AbstractMesh.prototype.getClassName = function () {
  20098. return "AbstractMesh";
  20099. };
  20100. /**
  20101. * Gets a string representation of the current mesh
  20102. * @param fullDetails defines a boolean indicating if full details must be included
  20103. * @returns a string representation of the current mesh
  20104. */
  20105. AbstractMesh.prototype.toString = function (fullDetails) {
  20106. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20107. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20108. if (this._skeleton) {
  20109. ret += ", skeleton: " + this._skeleton.name;
  20110. }
  20111. if (fullDetails) {
  20112. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20113. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20114. }
  20115. return ret;
  20116. };
  20117. /** @hidden */
  20118. AbstractMesh.prototype._rebuild = function () {
  20119. if (this._occlusionQuery) {
  20120. this._occlusionQuery = null;
  20121. }
  20122. if (this._edgesRenderer) {
  20123. this._edgesRenderer._rebuild();
  20124. }
  20125. if (!this.subMeshes) {
  20126. return;
  20127. }
  20128. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20129. var subMesh = _a[_i];
  20130. subMesh._rebuild();
  20131. }
  20132. };
  20133. /** @hidden */
  20134. AbstractMesh.prototype._resyncLightSources = function () {
  20135. this._lightSources.length = 0;
  20136. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20137. var light = _a[_i];
  20138. if (!light.isEnabled()) {
  20139. continue;
  20140. }
  20141. if (light.canAffectMesh(this)) {
  20142. this._lightSources.push(light);
  20143. }
  20144. }
  20145. this._markSubMeshesAsLightDirty();
  20146. };
  20147. /** @hidden */
  20148. AbstractMesh.prototype._resyncLighSource = function (light) {
  20149. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20150. var index = this._lightSources.indexOf(light);
  20151. if (index === -1) {
  20152. if (!isIn) {
  20153. return;
  20154. }
  20155. this._lightSources.push(light);
  20156. }
  20157. else {
  20158. if (isIn) {
  20159. return;
  20160. }
  20161. this._lightSources.splice(index, 1);
  20162. }
  20163. this._markSubMeshesAsLightDirty();
  20164. };
  20165. /** @hidden */
  20166. AbstractMesh.prototype._unBindEffect = function () {
  20167. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20168. var subMesh = _a[_i];
  20169. subMesh.setEffect(null);
  20170. }
  20171. };
  20172. /** @hidden */
  20173. AbstractMesh.prototype._removeLightSource = function (light) {
  20174. var index = this._lightSources.indexOf(light);
  20175. if (index === -1) {
  20176. return;
  20177. }
  20178. this._lightSources.splice(index, 1);
  20179. this._markSubMeshesAsLightDirty();
  20180. };
  20181. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20182. if (!this.subMeshes) {
  20183. return;
  20184. }
  20185. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20186. var subMesh = _a[_i];
  20187. if (subMesh._materialDefines) {
  20188. func(subMesh._materialDefines);
  20189. }
  20190. }
  20191. };
  20192. /** @hidden */
  20193. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20194. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20195. };
  20196. /** @hidden */
  20197. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20198. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20199. };
  20200. /** @hidden */
  20201. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20202. if (!this.subMeshes) {
  20203. return;
  20204. }
  20205. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20206. var subMesh = _a[_i];
  20207. var material = subMesh.getMaterial();
  20208. if (material) {
  20209. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20210. }
  20211. }
  20212. };
  20213. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20214. /**
  20215. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20216. */
  20217. get: function () {
  20218. return this._scaling;
  20219. },
  20220. set: function (newScaling) {
  20221. this._scaling = newScaling;
  20222. if (this.physicsImpostor) {
  20223. this.physicsImpostor.forceUpdate();
  20224. }
  20225. },
  20226. enumerable: true,
  20227. configurable: true
  20228. });
  20229. // Methods
  20230. /**
  20231. * Disables the mesh edge rendering mode
  20232. * @returns the currentAbstractMesh
  20233. */
  20234. AbstractMesh.prototype.disableEdgesRendering = function () {
  20235. if (this._edgesRenderer) {
  20236. this._edgesRenderer.dispose();
  20237. this._edgesRenderer = null;
  20238. }
  20239. return this;
  20240. };
  20241. /**
  20242. * Enables the edge rendering mode on the mesh.
  20243. * This mode makes the mesh edges visible
  20244. * @param epsilon defines the maximal distance between two angles to detect a face
  20245. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20246. * @returns the currentAbstractMesh
  20247. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20248. */
  20249. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20250. if (epsilon === void 0) { epsilon = 0.95; }
  20251. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20252. this.disableEdgesRendering();
  20253. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20254. return this;
  20255. };
  20256. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20257. /**
  20258. * Gets the edgesRenderer associated with the mesh
  20259. */
  20260. get: function () {
  20261. return this._edgesRenderer;
  20262. },
  20263. enumerable: true,
  20264. configurable: true
  20265. });
  20266. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20267. /**
  20268. * Returns true if the mesh is blocked. Implemented by child classes
  20269. */
  20270. get: function () {
  20271. return false;
  20272. },
  20273. enumerable: true,
  20274. configurable: true
  20275. });
  20276. /**
  20277. * Returns the mesh itself by default. Implemented by child classes
  20278. * @param camera defines the camera to use to pick the right LOD level
  20279. * @returns the currentAbstractMesh
  20280. */
  20281. AbstractMesh.prototype.getLOD = function (camera) {
  20282. return this;
  20283. };
  20284. /**
  20285. * Returns 0 by default. Implemented by child classes
  20286. * @returns an integer
  20287. */
  20288. AbstractMesh.prototype.getTotalVertices = function () {
  20289. return 0;
  20290. };
  20291. /**
  20292. * Returns null by default. Implemented by child classes
  20293. * @returns null
  20294. */
  20295. AbstractMesh.prototype.getIndices = function () {
  20296. return null;
  20297. };
  20298. /**
  20299. * Returns the array of the requested vertex data kind. Implemented by child classes
  20300. * @param kind defines the vertex data kind to use
  20301. * @returns null
  20302. */
  20303. AbstractMesh.prototype.getVerticesData = function (kind) {
  20304. return null;
  20305. };
  20306. /**
  20307. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20308. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20309. * Note that a new underlying VertexBuffer object is created each call.
  20310. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20311. * @param kind defines vertex data kind:
  20312. * * BABYLON.VertexBuffer.PositionKind
  20313. * * BABYLON.VertexBuffer.UVKind
  20314. * * BABYLON.VertexBuffer.UV2Kind
  20315. * * BABYLON.VertexBuffer.UV3Kind
  20316. * * BABYLON.VertexBuffer.UV4Kind
  20317. * * BABYLON.VertexBuffer.UV5Kind
  20318. * * BABYLON.VertexBuffer.UV6Kind
  20319. * * BABYLON.VertexBuffer.ColorKind
  20320. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20321. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20322. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20323. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20324. * @param data defines the data source
  20325. * @param updatable defines if the data must be flagged as updatable (or static)
  20326. * @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
  20327. * @returns the current mesh
  20328. */
  20329. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20330. return this;
  20331. };
  20332. /**
  20333. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20334. * If the mesh has no geometry, it is simply returned as it is.
  20335. * @param kind defines vertex data kind:
  20336. * * BABYLON.VertexBuffer.PositionKind
  20337. * * BABYLON.VertexBuffer.UVKind
  20338. * * BABYLON.VertexBuffer.UV2Kind
  20339. * * BABYLON.VertexBuffer.UV3Kind
  20340. * * BABYLON.VertexBuffer.UV4Kind
  20341. * * BABYLON.VertexBuffer.UV5Kind
  20342. * * BABYLON.VertexBuffer.UV6Kind
  20343. * * BABYLON.VertexBuffer.ColorKind
  20344. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20345. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20346. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20347. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20348. * @param data defines the data source
  20349. * @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
  20350. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20351. * @returns the current mesh
  20352. */
  20353. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20354. return this;
  20355. };
  20356. /**
  20357. * Sets the mesh indices,
  20358. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20359. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20360. * @param totalVertices Defines the total number of vertices
  20361. * @returns the current mesh
  20362. */
  20363. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20364. return this;
  20365. };
  20366. /**
  20367. * Gets a boolean indicating if specific vertex data is present
  20368. * @param kind defines the vertex data kind to use
  20369. * @returns true is data kind is present
  20370. */
  20371. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20372. return false;
  20373. };
  20374. /**
  20375. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20376. * @returns a BoundingInfo
  20377. */
  20378. AbstractMesh.prototype.getBoundingInfo = function () {
  20379. if (this._masterMesh) {
  20380. return this._masterMesh.getBoundingInfo();
  20381. }
  20382. if (!this._boundingInfo) {
  20383. // this._boundingInfo is being created here
  20384. this._updateBoundingInfo();
  20385. }
  20386. // cannot be null.
  20387. return this._boundingInfo;
  20388. };
  20389. /**
  20390. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20391. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20392. * @returns the current mesh
  20393. */
  20394. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20395. if (includeDescendants === void 0) { includeDescendants = true; }
  20396. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20397. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20398. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20399. if (maxDimension === 0) {
  20400. return this;
  20401. }
  20402. var scale = 1 / maxDimension;
  20403. this.scaling.scaleInPlace(scale);
  20404. return this;
  20405. };
  20406. /**
  20407. * Overwrite the current bounding info
  20408. * @param boundingInfo defines the new bounding info
  20409. * @returns the current mesh
  20410. */
  20411. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20412. this._boundingInfo = boundingInfo;
  20413. return this;
  20414. };
  20415. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20416. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20417. get: function () {
  20418. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20419. },
  20420. enumerable: true,
  20421. configurable: true
  20422. });
  20423. /** @hidden */
  20424. AbstractMesh.prototype._preActivate = function () {
  20425. };
  20426. /** @hidden */
  20427. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20428. };
  20429. /** @hidden */
  20430. AbstractMesh.prototype._activate = function (renderId) {
  20431. this._renderId = renderId;
  20432. };
  20433. /**
  20434. * Gets the current world matrix
  20435. * @returns a Matrix
  20436. */
  20437. AbstractMesh.prototype.getWorldMatrix = function () {
  20438. if (this._masterMesh) {
  20439. return this._masterMesh.getWorldMatrix();
  20440. }
  20441. return _super.prototype.getWorldMatrix.call(this);
  20442. };
  20443. /** @hidden */
  20444. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20445. if (this._masterMesh) {
  20446. return this._masterMesh._getWorldMatrixDeterminant();
  20447. }
  20448. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20449. };
  20450. // ================================== Point of View Movement =================================
  20451. /**
  20452. * Perform relative position change from the point of view of behind the front of the mesh.
  20453. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20454. * Supports definition of mesh facing forward or backward
  20455. * @param amountRight defines the distance on the right axis
  20456. * @param amountUp defines the distance on the up axis
  20457. * @param amountForward defines the distance on the forward axis
  20458. * @returns the current mesh
  20459. */
  20460. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20461. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20462. return this;
  20463. };
  20464. /**
  20465. * Calculate relative position change from the point of view of behind the front of the mesh.
  20466. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20467. * Supports definition of mesh facing forward or backward
  20468. * @param amountRight defines the distance on the right axis
  20469. * @param amountUp defines the distance on the up axis
  20470. * @param amountForward defines the distance on the forward axis
  20471. * @returns the new displacement vector
  20472. */
  20473. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20474. var rotMatrix = new BABYLON.Matrix();
  20475. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20476. rotQuaternion.toRotationMatrix(rotMatrix);
  20477. var translationDelta = BABYLON.Vector3.Zero();
  20478. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20479. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20480. return translationDelta;
  20481. };
  20482. // ================================== Point of View Rotation =================================
  20483. /**
  20484. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20485. * Supports definition of mesh facing forward or backward
  20486. * @param flipBack defines the flip
  20487. * @param twirlClockwise defines the twirl
  20488. * @param tiltRight defines the tilt
  20489. * @returns the current mesh
  20490. */
  20491. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20492. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20493. return this;
  20494. };
  20495. /**
  20496. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20497. * Supports definition of mesh facing forward or backward.
  20498. * @param flipBack defines the flip
  20499. * @param twirlClockwise defines the twirl
  20500. * @param tiltRight defines the tilt
  20501. * @returns the new rotation vector
  20502. */
  20503. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20504. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20505. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20506. };
  20507. /**
  20508. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20509. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20510. * @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
  20511. * @returns the new bounding vectors
  20512. */
  20513. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20514. if (includeDescendants === void 0) { includeDescendants = true; }
  20515. if (predicate === void 0) { predicate = null; }
  20516. // Ensures that all world matrix will be recomputed.
  20517. this.getScene().incrementRenderId();
  20518. this.computeWorldMatrix(true);
  20519. var min;
  20520. var max;
  20521. var boundingInfo = this.getBoundingInfo();
  20522. if (!this.subMeshes) {
  20523. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20524. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20525. }
  20526. else {
  20527. min = boundingInfo.boundingBox.minimumWorld;
  20528. max = boundingInfo.boundingBox.maximumWorld;
  20529. }
  20530. if (includeDescendants) {
  20531. var descendants = this.getDescendants(false);
  20532. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20533. var descendant = descendants_1[_i];
  20534. var childMesh = descendant;
  20535. childMesh.computeWorldMatrix(true);
  20536. // Filters meshes based on custom predicate function.
  20537. if (predicate && !predicate(childMesh)) {
  20538. continue;
  20539. }
  20540. //make sure we have the needed params to get mix and max
  20541. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20542. continue;
  20543. }
  20544. var childBoundingInfo = childMesh.getBoundingInfo();
  20545. var boundingBox = childBoundingInfo.boundingBox;
  20546. var minBox = boundingBox.minimumWorld;
  20547. var maxBox = boundingBox.maximumWorld;
  20548. BABYLON.Tools.CheckExtends(minBox, min, max);
  20549. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20550. }
  20551. }
  20552. return {
  20553. min: min,
  20554. max: max
  20555. };
  20556. };
  20557. /** @hidden */
  20558. AbstractMesh.prototype._updateBoundingInfo = function () {
  20559. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20560. this._boundingInfo.update(this.worldMatrixFromCache);
  20561. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20562. return this;
  20563. };
  20564. /** @hidden */
  20565. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20566. if (!this.subMeshes) {
  20567. return this;
  20568. }
  20569. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20570. var subMesh = this.subMeshes[subIndex];
  20571. if (!subMesh.IsGlobal) {
  20572. subMesh.updateBoundingInfo(matrix);
  20573. }
  20574. }
  20575. return this;
  20576. };
  20577. /** @hidden */
  20578. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20579. // Bounding info
  20580. this._updateBoundingInfo();
  20581. };
  20582. /**
  20583. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20584. * A mesh is in the frustum if its bounding box intersects the frustum
  20585. * @param frustumPlanes defines the frustum to test
  20586. * @returns true if the mesh is in the frustum planes
  20587. */
  20588. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20589. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20590. };
  20591. /**
  20592. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20593. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20594. * @param frustumPlanes defines the frustum to test
  20595. * @returns true if the mesh is completely in the frustum planes
  20596. */
  20597. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20598. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20599. };
  20600. /**
  20601. * True if the mesh intersects another mesh or a SolidParticle object
  20602. * @param mesh defines a target mesh or SolidParticle to test
  20603. * @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)
  20604. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20605. * @returns true if there is an intersection
  20606. */
  20607. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20608. if (precise === void 0) { precise = false; }
  20609. if (!this._boundingInfo || !mesh._boundingInfo) {
  20610. return false;
  20611. }
  20612. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20613. return true;
  20614. }
  20615. if (includeDescendants) {
  20616. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20617. var child = _a[_i];
  20618. if (child.intersectsMesh(mesh, precise, true)) {
  20619. return true;
  20620. }
  20621. }
  20622. }
  20623. return false;
  20624. };
  20625. /**
  20626. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20627. * @param point defines the point to test
  20628. * @returns true if there is an intersection
  20629. */
  20630. AbstractMesh.prototype.intersectsPoint = function (point) {
  20631. if (!this._boundingInfo) {
  20632. return false;
  20633. }
  20634. return this._boundingInfo.intersectsPoint(point);
  20635. };
  20636. /**
  20637. * Gets the current physics impostor
  20638. * @see http://doc.babylonjs.com/features/physics_engine
  20639. * @returns a physics impostor or null
  20640. */
  20641. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20642. return this.physicsImpostor;
  20643. };
  20644. /**
  20645. * Gets the position of the current mesh in camera space
  20646. * @param camera defines the camera to use
  20647. * @returns a position
  20648. */
  20649. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20650. if (camera === void 0) { camera = null; }
  20651. if (!camera) {
  20652. camera = this.getScene().activeCamera;
  20653. }
  20654. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20655. };
  20656. /**
  20657. * Returns the distance from the mesh to the active camera
  20658. * @param camera defines the camera to use
  20659. * @returns the distance
  20660. */
  20661. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20662. if (camera === void 0) { camera = null; }
  20663. if (!camera) {
  20664. camera = this.getScene().activeCamera;
  20665. }
  20666. return this.absolutePosition.subtract(camera.position).length();
  20667. };
  20668. /**
  20669. * Apply a physic impulse to the mesh
  20670. * @param force defines the force to apply
  20671. * @param contactPoint defines where to apply the force
  20672. * @returns the current mesh
  20673. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20674. */
  20675. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20676. if (!this.physicsImpostor) {
  20677. return this;
  20678. }
  20679. this.physicsImpostor.applyImpulse(force, contactPoint);
  20680. return this;
  20681. };
  20682. /**
  20683. * Creates a physic joint between two meshes
  20684. * @param otherMesh defines the other mesh to use
  20685. * @param pivot1 defines the pivot to use on this mesh
  20686. * @param pivot2 defines the pivot to use on the other mesh
  20687. * @param options defines additional options (can be plugin dependent)
  20688. * @returns the current mesh
  20689. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20690. */
  20691. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20692. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20693. return this;
  20694. }
  20695. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20696. mainPivot: pivot1,
  20697. connectedPivot: pivot2,
  20698. nativeParams: options
  20699. });
  20700. return this;
  20701. };
  20702. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20703. // Collisions
  20704. /**
  20705. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20706. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20707. */
  20708. get: function () {
  20709. return this._checkCollisions;
  20710. },
  20711. set: function (collisionEnabled) {
  20712. this._checkCollisions = collisionEnabled;
  20713. if (this.getScene().workerCollisions) {
  20714. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20715. }
  20716. },
  20717. enumerable: true,
  20718. configurable: true
  20719. });
  20720. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20721. /**
  20722. * Gets Collider object used to compute collisions (not physics)
  20723. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20724. */
  20725. get: function () {
  20726. return this._collider;
  20727. },
  20728. enumerable: true,
  20729. configurable: true
  20730. });
  20731. /**
  20732. * Move the mesh using collision engine
  20733. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20734. * @param displacement defines the requested displacement vector
  20735. * @returns the current mesh
  20736. */
  20737. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20738. var globalPosition = this.getAbsolutePosition();
  20739. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20740. if (!this._collider) {
  20741. this._collider = new BABYLON.Collider();
  20742. }
  20743. this._collider._radius = this.ellipsoid;
  20744. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20745. return this;
  20746. };
  20747. // Submeshes octree
  20748. /**
  20749. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20750. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20751. * @param maxCapacity defines the maximum size of each block (64 by default)
  20752. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20753. * @returns the new octree
  20754. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20755. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20756. */
  20757. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20758. if (maxCapacity === void 0) { maxCapacity = 64; }
  20759. if (maxDepth === void 0) { maxDepth = 2; }
  20760. if (!this._submeshesOctree) {
  20761. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20762. }
  20763. this.computeWorldMatrix(true);
  20764. var boundingInfo = this.getBoundingInfo();
  20765. // Update octree
  20766. var bbox = boundingInfo.boundingBox;
  20767. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20768. return this._submeshesOctree;
  20769. };
  20770. // Collisions
  20771. /** @hidden */
  20772. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20773. this._generatePointsArray();
  20774. if (!this._positions) {
  20775. return this;
  20776. }
  20777. // Transformation
  20778. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20779. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20780. subMesh._lastColliderWorldVertices = [];
  20781. subMesh._trianglePlanes = [];
  20782. var start = subMesh.verticesStart;
  20783. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20784. for (var i = start; i < end; i++) {
  20785. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20786. }
  20787. }
  20788. // Collide
  20789. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20790. if (collider.collisionFound) {
  20791. collider.collidedMesh = this;
  20792. }
  20793. return this;
  20794. };
  20795. /** @hidden */
  20796. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20797. var subMeshes;
  20798. var len;
  20799. // Octrees
  20800. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20801. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20802. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20803. len = intersections.length;
  20804. subMeshes = intersections.data;
  20805. }
  20806. else {
  20807. subMeshes = this.subMeshes;
  20808. len = subMeshes.length;
  20809. }
  20810. for (var index = 0; index < len; index++) {
  20811. var subMesh = subMeshes[index];
  20812. // Bounding test
  20813. if (len > 1 && !subMesh._checkCollision(collider))
  20814. continue;
  20815. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20816. }
  20817. return this;
  20818. };
  20819. /** @hidden */
  20820. AbstractMesh.prototype._checkCollision = function (collider) {
  20821. // Bounding box test
  20822. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20823. return this;
  20824. // Transformation matrix
  20825. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20826. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20827. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20828. return this;
  20829. };
  20830. // Picking
  20831. /** @hidden */
  20832. AbstractMesh.prototype._generatePointsArray = function () {
  20833. return false;
  20834. };
  20835. /**
  20836. * Checks if the passed Ray intersects with the mesh
  20837. * @param ray defines the ray to use
  20838. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20839. * @returns the picking info
  20840. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20841. */
  20842. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20843. var pickingInfo = new BABYLON.PickingInfo();
  20844. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20845. return pickingInfo;
  20846. }
  20847. if (!this._generatePointsArray()) {
  20848. return pickingInfo;
  20849. }
  20850. var intersectInfo = null;
  20851. // Octrees
  20852. var subMeshes;
  20853. var len;
  20854. if (this._submeshesOctree && this.useOctreeForPicking) {
  20855. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20856. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20857. len = intersections.length;
  20858. subMeshes = intersections.data;
  20859. }
  20860. else {
  20861. subMeshes = this.subMeshes;
  20862. len = subMeshes.length;
  20863. }
  20864. for (var index = 0; index < len; index++) {
  20865. var subMesh = subMeshes[index];
  20866. // Bounding test
  20867. if (len > 1 && !subMesh.canIntersects(ray))
  20868. continue;
  20869. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20870. if (currentIntersectInfo) {
  20871. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20872. intersectInfo = currentIntersectInfo;
  20873. intersectInfo.subMeshId = index;
  20874. if (fastCheck) {
  20875. break;
  20876. }
  20877. }
  20878. }
  20879. }
  20880. if (intersectInfo) {
  20881. // Get picked point
  20882. var world = this.getWorldMatrix();
  20883. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20884. var direction = ray.direction.clone();
  20885. direction = direction.scale(intersectInfo.distance);
  20886. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20887. var pickedPoint = worldOrigin.add(worldDirection);
  20888. // Return result
  20889. pickingInfo.hit = true;
  20890. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20891. pickingInfo.pickedPoint = pickedPoint;
  20892. pickingInfo.pickedMesh = this;
  20893. pickingInfo.bu = intersectInfo.bu || 0;
  20894. pickingInfo.bv = intersectInfo.bv || 0;
  20895. pickingInfo.faceId = intersectInfo.faceId;
  20896. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20897. return pickingInfo;
  20898. }
  20899. return pickingInfo;
  20900. };
  20901. /**
  20902. * Clones the current mesh
  20903. * @param name defines the mesh name
  20904. * @param newParent defines the new mesh parent
  20905. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20906. * @returns the new mesh
  20907. */
  20908. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20909. return null;
  20910. };
  20911. /**
  20912. * Disposes all the submeshes of the current meshnp
  20913. * @returns the current mesh
  20914. */
  20915. AbstractMesh.prototype.releaseSubMeshes = function () {
  20916. if (this.subMeshes) {
  20917. while (this.subMeshes.length) {
  20918. this.subMeshes[0].dispose();
  20919. }
  20920. }
  20921. else {
  20922. this.subMeshes = new Array();
  20923. }
  20924. return this;
  20925. };
  20926. /**
  20927. * Releases resources associated with this abstract mesh.
  20928. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20929. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20930. */
  20931. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20932. var _this = this;
  20933. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20934. var index;
  20935. // Smart Array Retainers.
  20936. this.getScene().freeActiveMeshes();
  20937. this.getScene().freeRenderingGroups();
  20938. // Action manager
  20939. if (this.actionManager !== undefined && this.actionManager !== null) {
  20940. this.actionManager.dispose();
  20941. this.actionManager = null;
  20942. }
  20943. // Skeleton
  20944. this._skeleton = null;
  20945. // Physics
  20946. if (this.physicsImpostor) {
  20947. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20948. }
  20949. // Intersections in progress
  20950. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20951. var other = this._intersectionsInProgress[index];
  20952. var pos = other._intersectionsInProgress.indexOf(this);
  20953. other._intersectionsInProgress.splice(pos, 1);
  20954. }
  20955. this._intersectionsInProgress = [];
  20956. // Lights
  20957. var lights = this.getScene().lights;
  20958. lights.forEach(function (light) {
  20959. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20960. if (meshIndex !== -1) {
  20961. light.includedOnlyMeshes.splice(meshIndex, 1);
  20962. }
  20963. meshIndex = light.excludedMeshes.indexOf(_this);
  20964. if (meshIndex !== -1) {
  20965. light.excludedMeshes.splice(meshIndex, 1);
  20966. }
  20967. // Shadow generators
  20968. var generator = light.getShadowGenerator();
  20969. if (generator) {
  20970. var shadowMap = generator.getShadowMap();
  20971. if (shadowMap && shadowMap.renderList) {
  20972. meshIndex = shadowMap.renderList.indexOf(_this);
  20973. if (meshIndex !== -1) {
  20974. shadowMap.renderList.splice(meshIndex, 1);
  20975. }
  20976. }
  20977. }
  20978. });
  20979. // Edges
  20980. if (this._edgesRenderer) {
  20981. this._edgesRenderer.dispose();
  20982. this._edgesRenderer = null;
  20983. }
  20984. // SubMeshes
  20985. if (this.getClassName() !== "InstancedMesh") {
  20986. this.releaseSubMeshes();
  20987. }
  20988. // Octree
  20989. var sceneOctree = this.getScene().selectionOctree;
  20990. if (sceneOctree !== undefined && sceneOctree !== null) {
  20991. var index = sceneOctree.dynamicContent.indexOf(this);
  20992. if (index !== -1) {
  20993. sceneOctree.dynamicContent.splice(index, 1);
  20994. }
  20995. }
  20996. // Query
  20997. var engine = this.getScene().getEngine();
  20998. if (this._occlusionQuery) {
  20999. this._isOcclusionQueryInProgress = false;
  21000. engine.deleteQuery(this._occlusionQuery);
  21001. this._occlusionQuery = null;
  21002. }
  21003. // Engine
  21004. engine.wipeCaches();
  21005. // Remove from scene
  21006. this.getScene().removeMesh(this);
  21007. if (disposeMaterialAndTextures) {
  21008. if (this.material) {
  21009. this.material.dispose(false, true);
  21010. }
  21011. }
  21012. if (!doNotRecurse) {
  21013. // Particles
  21014. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21015. if (this.getScene().particleSystems[index].emitter === this) {
  21016. this.getScene().particleSystems[index].dispose();
  21017. index--;
  21018. }
  21019. }
  21020. }
  21021. // facet data
  21022. if (this._facetDataEnabled) {
  21023. this.disableFacetData();
  21024. }
  21025. this.onAfterWorldMatrixUpdateObservable.clear();
  21026. this.onCollideObservable.clear();
  21027. this.onCollisionPositionChangeObservable.clear();
  21028. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21029. };
  21030. /**
  21031. * Adds the passed mesh as a child to the current mesh
  21032. * @param mesh defines the child mesh
  21033. * @returns the current mesh
  21034. */
  21035. AbstractMesh.prototype.addChild = function (mesh) {
  21036. mesh.setParent(this);
  21037. return this;
  21038. };
  21039. /**
  21040. * Removes the passed mesh from the current mesh children list
  21041. * @param mesh defines the child mesh
  21042. * @returns the current mesh
  21043. */
  21044. AbstractMesh.prototype.removeChild = function (mesh) {
  21045. mesh.setParent(null);
  21046. return this;
  21047. };
  21048. // Facet data
  21049. /** @hidden */
  21050. AbstractMesh.prototype._initFacetData = function () {
  21051. if (!this._facetNormals) {
  21052. this._facetNormals = new Array();
  21053. }
  21054. if (!this._facetPositions) {
  21055. this._facetPositions = new Array();
  21056. }
  21057. if (!this._facetPartitioning) {
  21058. this._facetPartitioning = new Array();
  21059. }
  21060. this._facetNb = (this.getIndices().length / 3) | 0;
  21061. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21062. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21063. for (var f = 0; f < this._facetNb; f++) {
  21064. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21065. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21066. }
  21067. this._facetDataEnabled = true;
  21068. return this;
  21069. };
  21070. /**
  21071. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21072. * This method can be called within the render loop.
  21073. * 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
  21074. * @returns the current mesh
  21075. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21076. */
  21077. AbstractMesh.prototype.updateFacetData = function () {
  21078. if (!this._facetDataEnabled) {
  21079. this._initFacetData();
  21080. }
  21081. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21082. var indices = this.getIndices();
  21083. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21084. var bInfo = this.getBoundingInfo();
  21085. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21086. // init arrays, matrix and sort function on first call
  21087. this._facetDepthSortEnabled = true;
  21088. if (indices instanceof Uint16Array) {
  21089. this._depthSortedIndices = new Uint16Array(indices);
  21090. }
  21091. else if (indices instanceof Uint32Array) {
  21092. this._depthSortedIndices = new Uint32Array(indices);
  21093. }
  21094. else {
  21095. var needs32bits = false;
  21096. for (var i = 0; i < indices.length; i++) {
  21097. if (indices[i] > 65535) {
  21098. needs32bits = true;
  21099. break;
  21100. }
  21101. }
  21102. if (needs32bits) {
  21103. this._depthSortedIndices = new Uint32Array(indices);
  21104. }
  21105. else {
  21106. this._depthSortedIndices = new Uint16Array(indices);
  21107. }
  21108. }
  21109. this._facetDepthSortFunction = function (f1, f2) {
  21110. return (f2.sqDistance - f1.sqDistance);
  21111. };
  21112. if (!this._facetDepthSortFrom) {
  21113. var camera = this.getScene().activeCamera;
  21114. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21115. }
  21116. this._depthSortedFacets = [];
  21117. for (var f = 0; f < this._facetNb; f++) {
  21118. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21119. this._depthSortedFacets.push(depthSortedFacet);
  21120. }
  21121. this._invertedMatrix = BABYLON.Matrix.Identity();
  21122. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21123. }
  21124. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21125. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21126. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21127. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21128. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21129. this._subDiv.max = this._partitioningSubdivisions;
  21130. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21131. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21132. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21133. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21134. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21135. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21136. // set the parameters for ComputeNormals()
  21137. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21138. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21139. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21140. this._facetParameters.bInfo = bInfo;
  21141. this._facetParameters.bbSize = this._bbSize;
  21142. this._facetParameters.subDiv = this._subDiv;
  21143. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21144. this._facetParameters.depthSort = this._facetDepthSort;
  21145. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21146. this.computeWorldMatrix(true);
  21147. this._worldMatrix.invertToRef(this._invertedMatrix);
  21148. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21149. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21150. }
  21151. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21152. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21153. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21154. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21155. var l = (this._depthSortedIndices.length / 3) | 0;
  21156. for (var f = 0; f < l; f++) {
  21157. var sind = this._depthSortedFacets[f].ind;
  21158. this._depthSortedIndices[f * 3] = indices[sind];
  21159. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21160. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21161. }
  21162. this.updateIndices(this._depthSortedIndices);
  21163. }
  21164. return this;
  21165. };
  21166. /**
  21167. * Returns the facetLocalNormals array.
  21168. * The normals are expressed in the mesh local spac
  21169. * @returns an array of Vector3
  21170. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21171. */
  21172. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21173. if (!this._facetNormals) {
  21174. this.updateFacetData();
  21175. }
  21176. return this._facetNormals;
  21177. };
  21178. /**
  21179. * Returns the facetLocalPositions array.
  21180. * The facet positions are expressed in the mesh local space
  21181. * @returns an array of Vector3
  21182. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21183. */
  21184. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21185. if (!this._facetPositions) {
  21186. this.updateFacetData();
  21187. }
  21188. return this._facetPositions;
  21189. };
  21190. /**
  21191. * Returns the facetLocalPartioning array
  21192. * @returns an array of array of numbers
  21193. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21194. */
  21195. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21196. if (!this._facetPartitioning) {
  21197. this.updateFacetData();
  21198. }
  21199. return this._facetPartitioning;
  21200. };
  21201. /**
  21202. * Returns the i-th facet position in the world system.
  21203. * This method allocates a new Vector3 per call
  21204. * @param i defines the facet index
  21205. * @returns a new Vector3
  21206. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21207. */
  21208. AbstractMesh.prototype.getFacetPosition = function (i) {
  21209. var pos = BABYLON.Vector3.Zero();
  21210. this.getFacetPositionToRef(i, pos);
  21211. return pos;
  21212. };
  21213. /**
  21214. * Sets the reference Vector3 with the i-th facet position in the world system
  21215. * @param i defines the facet index
  21216. * @param ref defines the target vector
  21217. * @returns the current mesh
  21218. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21219. */
  21220. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21221. var localPos = (this.getFacetLocalPositions())[i];
  21222. var world = this.getWorldMatrix();
  21223. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21224. return this;
  21225. };
  21226. /**
  21227. * Returns the i-th facet normal in the world system.
  21228. * This method allocates a new Vector3 per call
  21229. * @param i defines the facet index
  21230. * @returns a new Vector3
  21231. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21232. */
  21233. AbstractMesh.prototype.getFacetNormal = function (i) {
  21234. var norm = BABYLON.Vector3.Zero();
  21235. this.getFacetNormalToRef(i, norm);
  21236. return norm;
  21237. };
  21238. /**
  21239. * Sets the reference Vector3 with the i-th facet normal in the world system
  21240. * @param i defines the facet index
  21241. * @param ref defines the target vector
  21242. * @returns the current mesh
  21243. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21244. */
  21245. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21246. var localNorm = (this.getFacetLocalNormals())[i];
  21247. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21248. return this;
  21249. };
  21250. /**
  21251. * 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)
  21252. * @param x defines x coordinate
  21253. * @param y defines y coordinate
  21254. * @param z defines z coordinate
  21255. * @returns the array of facet indexes
  21256. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21257. */
  21258. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21259. var bInfo = this.getBoundingInfo();
  21260. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21261. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21262. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21263. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21264. return null;
  21265. }
  21266. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21267. };
  21268. /**
  21269. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21270. * @param projected sets as the (x,y,z) world projection on the facet
  21271. * @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
  21272. * @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
  21273. * @param x defines x coordinate
  21274. * @param y defines y coordinate
  21275. * @param z defines z coordinate
  21276. * @returns the face index if found (or null instead)
  21277. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21278. */
  21279. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21280. if (checkFace === void 0) { checkFace = false; }
  21281. if (facing === void 0) { facing = true; }
  21282. var world = this.getWorldMatrix();
  21283. var invMat = BABYLON.Tmp.Matrix[5];
  21284. world.invertToRef(invMat);
  21285. var invVect = BABYLON.Tmp.Vector3[8];
  21286. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21287. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21288. if (projected) {
  21289. // tranform the local computed projected vector to world coordinates
  21290. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21291. }
  21292. return closest;
  21293. };
  21294. /**
  21295. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21296. * @param projected sets as the (x,y,z) local projection on the facet
  21297. * @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
  21298. * @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
  21299. * @param x defines x coordinate
  21300. * @param y defines y coordinate
  21301. * @param z defines z coordinate
  21302. * @returns the face index if found (or null instead)
  21303. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21304. */
  21305. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21306. if (checkFace === void 0) { checkFace = false; }
  21307. if (facing === void 0) { facing = true; }
  21308. var closest = null;
  21309. var tmpx = 0.0;
  21310. var tmpy = 0.0;
  21311. var tmpz = 0.0;
  21312. var d = 0.0; // tmp dot facet normal * facet position
  21313. var t0 = 0.0;
  21314. var projx = 0.0;
  21315. var projy = 0.0;
  21316. var projz = 0.0;
  21317. // Get all the facets in the same partitioning block than (x, y, z)
  21318. var facetPositions = this.getFacetLocalPositions();
  21319. var facetNormals = this.getFacetLocalNormals();
  21320. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21321. if (!facetsInBlock) {
  21322. return null;
  21323. }
  21324. // Get the closest facet to (x, y, z)
  21325. var shortest = Number.MAX_VALUE; // init distance vars
  21326. var tmpDistance = shortest;
  21327. var fib; // current facet in the block
  21328. var norm; // current facet normal
  21329. var p0; // current facet barycenter position
  21330. // loop on all the facets in the current partitioning block
  21331. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21332. fib = facetsInBlock[idx];
  21333. norm = facetNormals[fib];
  21334. p0 = facetPositions[fib];
  21335. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21336. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21337. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21338. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21339. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21340. projx = x + norm.x * t0;
  21341. projy = y + norm.y * t0;
  21342. projz = z + norm.z * t0;
  21343. tmpx = projx - x;
  21344. tmpy = projy - y;
  21345. tmpz = projz - z;
  21346. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21347. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21348. shortest = tmpDistance;
  21349. closest = fib;
  21350. if (projected) {
  21351. projected.x = projx;
  21352. projected.y = projy;
  21353. projected.z = projz;
  21354. }
  21355. }
  21356. }
  21357. }
  21358. return closest;
  21359. };
  21360. /**
  21361. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21362. * @returns the parameters
  21363. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21364. */
  21365. AbstractMesh.prototype.getFacetDataParameters = function () {
  21366. return this._facetParameters;
  21367. };
  21368. /**
  21369. * Disables the feature FacetData and frees the related memory
  21370. * @returns the current mesh
  21371. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21372. */
  21373. AbstractMesh.prototype.disableFacetData = function () {
  21374. if (this._facetDataEnabled) {
  21375. this._facetDataEnabled = false;
  21376. this._facetPositions = new Array();
  21377. this._facetNormals = new Array();
  21378. this._facetPartitioning = new Array();
  21379. this._facetParameters = null;
  21380. this._depthSortedIndices = new Uint32Array(0);
  21381. }
  21382. return this;
  21383. };
  21384. /**
  21385. * Updates the AbstractMesh indices array
  21386. * @param indices defines the data source
  21387. * @returns the current mesh
  21388. */
  21389. AbstractMesh.prototype.updateIndices = function (indices) {
  21390. return this;
  21391. };
  21392. /**
  21393. * Creates new normals data for the mesh
  21394. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21395. * @returns the current mesh
  21396. */
  21397. AbstractMesh.prototype.createNormals = function (updatable) {
  21398. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21399. var indices = this.getIndices();
  21400. var normals;
  21401. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21402. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21403. }
  21404. else {
  21405. normals = [];
  21406. }
  21407. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21408. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21409. return this;
  21410. };
  21411. /**
  21412. * Align the mesh with a normal
  21413. * @param normal defines the normal to use
  21414. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21415. * @returns the current mesh
  21416. */
  21417. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21418. if (!upDirection) {
  21419. upDirection = BABYLON.Axis.Y;
  21420. }
  21421. var axisX = BABYLON.Tmp.Vector3[0];
  21422. var axisZ = BABYLON.Tmp.Vector3[1];
  21423. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21424. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21425. if (this.rotationQuaternion) {
  21426. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21427. }
  21428. else {
  21429. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21430. }
  21431. return this;
  21432. };
  21433. /** @hidden */
  21434. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21435. var engine = this.getEngine();
  21436. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21437. this._isOccluded = false;
  21438. return;
  21439. }
  21440. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21441. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21442. if (isOcclusionQueryAvailable) {
  21443. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21444. this._isOcclusionQueryInProgress = false;
  21445. this._occlusionInternalRetryCounter = 0;
  21446. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21447. }
  21448. else {
  21449. this._occlusionInternalRetryCounter++;
  21450. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21451. this._isOcclusionQueryInProgress = false;
  21452. this._occlusionInternalRetryCounter = 0;
  21453. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21454. // if strict continue the last state of the object.
  21455. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21456. }
  21457. else {
  21458. return;
  21459. }
  21460. }
  21461. }
  21462. var scene = this.getScene();
  21463. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21464. if (!this._occlusionQuery) {
  21465. this._occlusionQuery = engine.createQuery();
  21466. }
  21467. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21468. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21469. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21470. this._isOcclusionQueryInProgress = true;
  21471. };
  21472. /** No occlusion */
  21473. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21474. /** Occlusion set to optimisitic */
  21475. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21476. /** Occlusion set to strict */
  21477. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21478. /** Use an accurante occlusion algorithm */
  21479. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21480. /** Use a conservative occlusion algorithm */
  21481. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21482. return AbstractMesh;
  21483. }(BABYLON.TransformNode));
  21484. BABYLON.AbstractMesh = AbstractMesh;
  21485. })(BABYLON || (BABYLON = {}));
  21486. //# sourceMappingURL=babylon.abstractMesh.js.map
  21487. var BABYLON;
  21488. (function (BABYLON) {
  21489. /**
  21490. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21491. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21492. * 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.
  21493. */
  21494. var Light = /** @class */ (function (_super) {
  21495. __extends(Light, _super);
  21496. /**
  21497. * Creates a Light object in the scene.
  21498. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21499. * @param name The firendly name of the light
  21500. * @param scene The scene the light belongs too
  21501. */
  21502. function Light(name, scene) {
  21503. var _this = _super.call(this, name, scene) || this;
  21504. /**
  21505. * Diffuse gives the basic color to an object.
  21506. */
  21507. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21508. /**
  21509. * Specular produces a highlight color on an object.
  21510. * Note: This is note affecting PBR materials.
  21511. */
  21512. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21513. /**
  21514. * Strength of the light.
  21515. * Note: By default it is define in the framework own unit.
  21516. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21517. */
  21518. _this.intensity = 1.0;
  21519. /**
  21520. * Defines how far from the source the light is impacting in scene units.
  21521. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21522. */
  21523. _this.range = Number.MAX_VALUE;
  21524. /**
  21525. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21526. * of light.
  21527. */
  21528. _this._photometricScale = 1.0;
  21529. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21530. _this._radius = 0.00001;
  21531. /**
  21532. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21533. * exceeding the number allowed of the materials.
  21534. */
  21535. _this.renderPriority = 0;
  21536. _this._shadowEnabled = true;
  21537. _this._excludeWithLayerMask = 0;
  21538. _this._includeOnlyWithLayerMask = 0;
  21539. _this._lightmapMode = 0;
  21540. /**
  21541. * @hidden Internal use only.
  21542. */
  21543. _this._excludedMeshesIds = new Array();
  21544. /**
  21545. * @hidden Internal use only.
  21546. */
  21547. _this._includedOnlyMeshesIds = new Array();
  21548. _this.getScene().addLight(_this);
  21549. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21550. _this._buildUniformLayout();
  21551. _this.includedOnlyMeshes = new Array();
  21552. _this.excludedMeshes = new Array();
  21553. _this._resyncMeshes();
  21554. return _this;
  21555. }
  21556. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21557. /**
  21558. * If every light affecting the material is in this lightmapMode,
  21559. * material.lightmapTexture adds or multiplies
  21560. * (depends on material.useLightmapAsShadowmap)
  21561. * after every other light calculations.
  21562. */
  21563. get: function () {
  21564. return Light._LIGHTMAP_DEFAULT;
  21565. },
  21566. enumerable: true,
  21567. configurable: true
  21568. });
  21569. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21570. /**
  21571. * material.lightmapTexture as only diffuse lighting from this light
  21572. * adds only specular lighting from this light
  21573. * adds dynamic shadows
  21574. */
  21575. get: function () {
  21576. return Light._LIGHTMAP_SPECULAR;
  21577. },
  21578. enumerable: true,
  21579. configurable: true
  21580. });
  21581. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21582. /**
  21583. * material.lightmapTexture as only lighting
  21584. * no light calculation from this light
  21585. * only adds dynamic shadows from this light
  21586. */
  21587. get: function () {
  21588. return Light._LIGHTMAP_SHADOWSONLY;
  21589. },
  21590. enumerable: true,
  21591. configurable: true
  21592. });
  21593. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21594. /**
  21595. * Each light type uses the default quantity according to its type:
  21596. * point/spot lights use luminous intensity
  21597. * directional lights use illuminance
  21598. */
  21599. get: function () {
  21600. return Light._INTENSITYMODE_AUTOMATIC;
  21601. },
  21602. enumerable: true,
  21603. configurable: true
  21604. });
  21605. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21606. /**
  21607. * lumen (lm)
  21608. */
  21609. get: function () {
  21610. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21611. },
  21612. enumerable: true,
  21613. configurable: true
  21614. });
  21615. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21616. /**
  21617. * candela (lm/sr)
  21618. */
  21619. get: function () {
  21620. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21621. },
  21622. enumerable: true,
  21623. configurable: true
  21624. });
  21625. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21626. /**
  21627. * lux (lm/m^2)
  21628. */
  21629. get: function () {
  21630. return Light._INTENSITYMODE_ILLUMINANCE;
  21631. },
  21632. enumerable: true,
  21633. configurable: true
  21634. });
  21635. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21636. /**
  21637. * nit (cd/m^2)
  21638. */
  21639. get: function () {
  21640. return Light._INTENSITYMODE_LUMINANCE;
  21641. },
  21642. enumerable: true,
  21643. configurable: true
  21644. });
  21645. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21646. /**
  21647. * Light type const id of the point light.
  21648. */
  21649. get: function () {
  21650. return Light._LIGHTTYPEID_POINTLIGHT;
  21651. },
  21652. enumerable: true,
  21653. configurable: true
  21654. });
  21655. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21656. /**
  21657. * Light type const id of the directional light.
  21658. */
  21659. get: function () {
  21660. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21661. },
  21662. enumerable: true,
  21663. configurable: true
  21664. });
  21665. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21666. /**
  21667. * Light type const id of the spot light.
  21668. */
  21669. get: function () {
  21670. return Light._LIGHTTYPEID_SPOTLIGHT;
  21671. },
  21672. enumerable: true,
  21673. configurable: true
  21674. });
  21675. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21676. /**
  21677. * Light type const id of the hemispheric light.
  21678. */
  21679. get: function () {
  21680. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21681. },
  21682. enumerable: true,
  21683. configurable: true
  21684. });
  21685. Object.defineProperty(Light.prototype, "intensityMode", {
  21686. /**
  21687. * Gets the photometric scale used to interpret the intensity.
  21688. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21689. */
  21690. get: function () {
  21691. return this._intensityMode;
  21692. },
  21693. /**
  21694. * Sets the photometric scale used to interpret the intensity.
  21695. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21696. */
  21697. set: function (value) {
  21698. this._intensityMode = value;
  21699. this._computePhotometricScale();
  21700. },
  21701. enumerable: true,
  21702. configurable: true
  21703. });
  21704. ;
  21705. ;
  21706. Object.defineProperty(Light.prototype, "radius", {
  21707. /**
  21708. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21709. */
  21710. get: function () {
  21711. return this._radius;
  21712. },
  21713. /**
  21714. * sets the light radius used by PBR Materials to simulate soft area lights.
  21715. */
  21716. set: function (value) {
  21717. this._radius = value;
  21718. this._computePhotometricScale();
  21719. },
  21720. enumerable: true,
  21721. configurable: true
  21722. });
  21723. ;
  21724. ;
  21725. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21726. /**
  21727. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21728. * the current shadow generator.
  21729. */
  21730. get: function () {
  21731. return this._shadowEnabled;
  21732. },
  21733. /**
  21734. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21735. * the current shadow generator.
  21736. */
  21737. set: function (value) {
  21738. if (this._shadowEnabled === value) {
  21739. return;
  21740. }
  21741. this._shadowEnabled = value;
  21742. this._markMeshesAsLightDirty();
  21743. },
  21744. enumerable: true,
  21745. configurable: true
  21746. });
  21747. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21748. /**
  21749. * Gets the only meshes impacted by this light.
  21750. */
  21751. get: function () {
  21752. return this._includedOnlyMeshes;
  21753. },
  21754. /**
  21755. * Sets the only meshes impacted by this light.
  21756. */
  21757. set: function (value) {
  21758. this._includedOnlyMeshes = value;
  21759. this._hookArrayForIncludedOnly(value);
  21760. },
  21761. enumerable: true,
  21762. configurable: true
  21763. });
  21764. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21765. /**
  21766. * Gets the meshes not impacted by this light.
  21767. */
  21768. get: function () {
  21769. return this._excludedMeshes;
  21770. },
  21771. /**
  21772. * Sets the meshes not impacted by this light.
  21773. */
  21774. set: function (value) {
  21775. this._excludedMeshes = value;
  21776. this._hookArrayForExcluded(value);
  21777. },
  21778. enumerable: true,
  21779. configurable: true
  21780. });
  21781. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21782. /**
  21783. * Gets the layer id use to find what meshes are not impacted by the light.
  21784. * Inactive if 0
  21785. */
  21786. get: function () {
  21787. return this._excludeWithLayerMask;
  21788. },
  21789. /**
  21790. * Sets the layer id use to find what meshes are not impacted by the light.
  21791. * Inactive if 0
  21792. */
  21793. set: function (value) {
  21794. this._excludeWithLayerMask = value;
  21795. this._resyncMeshes();
  21796. },
  21797. enumerable: true,
  21798. configurable: true
  21799. });
  21800. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21801. /**
  21802. * Gets the layer id use to find what meshes are impacted by the light.
  21803. * Inactive if 0
  21804. */
  21805. get: function () {
  21806. return this._includeOnlyWithLayerMask;
  21807. },
  21808. /**
  21809. * Sets the layer id use to find what meshes are impacted by the light.
  21810. * Inactive if 0
  21811. */
  21812. set: function (value) {
  21813. this._includeOnlyWithLayerMask = value;
  21814. this._resyncMeshes();
  21815. },
  21816. enumerable: true,
  21817. configurable: true
  21818. });
  21819. Object.defineProperty(Light.prototype, "lightmapMode", {
  21820. /**
  21821. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21822. */
  21823. get: function () {
  21824. return this._lightmapMode;
  21825. },
  21826. /**
  21827. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21828. */
  21829. set: function (value) {
  21830. if (this._lightmapMode === value) {
  21831. return;
  21832. }
  21833. this._lightmapMode = value;
  21834. this._markMeshesAsLightDirty();
  21835. },
  21836. enumerable: true,
  21837. configurable: true
  21838. });
  21839. /**
  21840. * Returns the string "Light".
  21841. * @returns the class name
  21842. */
  21843. Light.prototype.getClassName = function () {
  21844. return "Light";
  21845. };
  21846. /**
  21847. * Converts the light information to a readable string for debug purpose.
  21848. * @param fullDetails Supports for multiple levels of logging within scene loading
  21849. * @returns the human readable light info
  21850. */
  21851. Light.prototype.toString = function (fullDetails) {
  21852. var ret = "Name: " + this.name;
  21853. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21854. if (this.animations) {
  21855. for (var i = 0; i < this.animations.length; i++) {
  21856. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21857. }
  21858. }
  21859. if (fullDetails) {
  21860. }
  21861. return ret;
  21862. };
  21863. /**
  21864. * Set the enabled state of this node.
  21865. * @param value - the new enabled state
  21866. */
  21867. Light.prototype.setEnabled = function (value) {
  21868. _super.prototype.setEnabled.call(this, value);
  21869. this._resyncMeshes();
  21870. };
  21871. /**
  21872. * Returns the Light associated shadow generator if any.
  21873. * @return the associated shadow generator.
  21874. */
  21875. Light.prototype.getShadowGenerator = function () {
  21876. return this._shadowGenerator;
  21877. };
  21878. /**
  21879. * Returns a Vector3, the absolute light position in the World.
  21880. * @returns the world space position of the light
  21881. */
  21882. Light.prototype.getAbsolutePosition = function () {
  21883. return BABYLON.Vector3.Zero();
  21884. };
  21885. /**
  21886. * Specifies if the light will affect the passed mesh.
  21887. * @param mesh The mesh to test against the light
  21888. * @return true the mesh is affected otherwise, false.
  21889. */
  21890. Light.prototype.canAffectMesh = function (mesh) {
  21891. if (!mesh) {
  21892. return true;
  21893. }
  21894. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21895. return false;
  21896. }
  21897. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21898. return false;
  21899. }
  21900. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21901. return false;
  21902. }
  21903. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21904. return false;
  21905. }
  21906. return true;
  21907. };
  21908. /**
  21909. * Computes and Returns the light World matrix.
  21910. * @returns the world matrix
  21911. */
  21912. Light.prototype.getWorldMatrix = function () {
  21913. this._currentRenderId = this.getScene().getRenderId();
  21914. this._childRenderId = this._currentRenderId;
  21915. var worldMatrix = this._getWorldMatrix();
  21916. if (this.parent && this.parent.getWorldMatrix) {
  21917. if (!this._parentedWorldMatrix) {
  21918. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21919. }
  21920. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21921. this._markSyncedWithParent();
  21922. return this._parentedWorldMatrix;
  21923. }
  21924. return worldMatrix;
  21925. };
  21926. /**
  21927. * Sort function to order lights for rendering.
  21928. * @param a First Light object to compare to second.
  21929. * @param b Second Light object to compare first.
  21930. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21931. */
  21932. Light.CompareLightsPriority = function (a, b) {
  21933. //shadow-casting lights have priority over non-shadow-casting lights
  21934. //the renderPrioirty is a secondary sort criterion
  21935. if (a.shadowEnabled !== b.shadowEnabled) {
  21936. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21937. }
  21938. return b.renderPriority - a.renderPriority;
  21939. };
  21940. /**
  21941. * Releases resources associated with this node.
  21942. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21943. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21944. */
  21945. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21946. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21947. if (this._shadowGenerator) {
  21948. this._shadowGenerator.dispose();
  21949. this._shadowGenerator = null;
  21950. }
  21951. // Animations
  21952. this.getScene().stopAnimation(this);
  21953. // Remove from meshes
  21954. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21955. var mesh = _a[_i];
  21956. mesh._removeLightSource(this);
  21957. }
  21958. this._uniformBuffer.dispose();
  21959. // Remove from scene
  21960. this.getScene().removeLight(this);
  21961. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21962. };
  21963. /**
  21964. * Returns the light type ID (integer).
  21965. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21966. */
  21967. Light.prototype.getTypeID = function () {
  21968. return 0;
  21969. };
  21970. /**
  21971. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21972. * @returns the scaled intensity in intensity mode unit
  21973. */
  21974. Light.prototype.getScaledIntensity = function () {
  21975. return this._photometricScale * this.intensity;
  21976. };
  21977. /**
  21978. * Returns a new Light object, named "name", from the current one.
  21979. * @param name The name of the cloned light
  21980. * @returns the new created light
  21981. */
  21982. Light.prototype.clone = function (name) {
  21983. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21984. if (!constructor) {
  21985. return null;
  21986. }
  21987. return BABYLON.SerializationHelper.Clone(constructor, this);
  21988. };
  21989. /**
  21990. * Serializes the current light into a Serialization object.
  21991. * @returns the serialized object.
  21992. */
  21993. Light.prototype.serialize = function () {
  21994. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21995. // Type
  21996. serializationObject.type = this.getTypeID();
  21997. // Parent
  21998. if (this.parent) {
  21999. serializationObject.parentId = this.parent.id;
  22000. }
  22001. // Inclusion / exclusions
  22002. if (this.excludedMeshes.length > 0) {
  22003. serializationObject.excludedMeshesIds = [];
  22004. this.excludedMeshes.forEach(function (mesh) {
  22005. serializationObject.excludedMeshesIds.push(mesh.id);
  22006. });
  22007. }
  22008. if (this.includedOnlyMeshes.length > 0) {
  22009. serializationObject.includedOnlyMeshesIds = [];
  22010. this.includedOnlyMeshes.forEach(function (mesh) {
  22011. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22012. });
  22013. }
  22014. // Animations
  22015. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22016. serializationObject.ranges = this.serializeAnimationRanges();
  22017. return serializationObject;
  22018. };
  22019. /**
  22020. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22021. * This new light is named "name" and added to the passed scene.
  22022. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22023. * @param name The friendly name of the light
  22024. * @param scene The scene the new light will belong to
  22025. * @returns the constructor function
  22026. */
  22027. Light.GetConstructorFromName = function (type, name, scene) {
  22028. switch (type) {
  22029. case 0:
  22030. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  22031. case 1:
  22032. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  22033. case 2:
  22034. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  22035. case 3:
  22036. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  22037. }
  22038. return null;
  22039. };
  22040. /**
  22041. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22042. * @param parsedLight The JSON representation of the light
  22043. * @param scene The scene to create the parsed light in
  22044. * @returns the created light after parsing
  22045. */
  22046. Light.Parse = function (parsedLight, scene) {
  22047. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22048. if (!constructor) {
  22049. return null;
  22050. }
  22051. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22052. // Inclusion / exclusions
  22053. if (parsedLight.excludedMeshesIds) {
  22054. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22055. }
  22056. if (parsedLight.includedOnlyMeshesIds) {
  22057. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22058. }
  22059. // Parent
  22060. if (parsedLight.parentId) {
  22061. light._waitingParentId = parsedLight.parentId;
  22062. }
  22063. // Animations
  22064. if (parsedLight.animations) {
  22065. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22066. var parsedAnimation = parsedLight.animations[animationIndex];
  22067. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22068. }
  22069. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22070. }
  22071. if (parsedLight.autoAnimate) {
  22072. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22073. }
  22074. return light;
  22075. };
  22076. Light.prototype._hookArrayForExcluded = function (array) {
  22077. var _this = this;
  22078. var oldPush = array.push;
  22079. array.push = function () {
  22080. var items = [];
  22081. for (var _i = 0; _i < arguments.length; _i++) {
  22082. items[_i] = arguments[_i];
  22083. }
  22084. var result = oldPush.apply(array, items);
  22085. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22086. var item = items_1[_a];
  22087. item._resyncLighSource(_this);
  22088. }
  22089. return result;
  22090. };
  22091. var oldSplice = array.splice;
  22092. array.splice = function (index, deleteCount) {
  22093. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22094. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22095. var item = deleted_1[_i];
  22096. item._resyncLighSource(_this);
  22097. }
  22098. return deleted;
  22099. };
  22100. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22101. var item = array_1[_i];
  22102. item._resyncLighSource(this);
  22103. }
  22104. };
  22105. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22106. var _this = this;
  22107. var oldPush = array.push;
  22108. array.push = function () {
  22109. var items = [];
  22110. for (var _i = 0; _i < arguments.length; _i++) {
  22111. items[_i] = arguments[_i];
  22112. }
  22113. var result = oldPush.apply(array, items);
  22114. _this._resyncMeshes();
  22115. return result;
  22116. };
  22117. var oldSplice = array.splice;
  22118. array.splice = function (index, deleteCount) {
  22119. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22120. _this._resyncMeshes();
  22121. return deleted;
  22122. };
  22123. this._resyncMeshes();
  22124. };
  22125. Light.prototype._resyncMeshes = function () {
  22126. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22127. var mesh = _a[_i];
  22128. mesh._resyncLighSource(this);
  22129. }
  22130. };
  22131. /**
  22132. * Forces the meshes to update their light related information in their rendering used effects
  22133. * @hidden Internal Use Only
  22134. */
  22135. Light.prototype._markMeshesAsLightDirty = function () {
  22136. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22137. var mesh = _a[_i];
  22138. if (mesh._lightSources.indexOf(this) !== -1) {
  22139. mesh._markSubMeshesAsLightDirty();
  22140. }
  22141. }
  22142. };
  22143. /**
  22144. * Recomputes the cached photometric scale if needed.
  22145. */
  22146. Light.prototype._computePhotometricScale = function () {
  22147. this._photometricScale = this._getPhotometricScale();
  22148. this.getScene().resetCachedMaterial();
  22149. };
  22150. /**
  22151. * Returns the Photometric Scale according to the light type and intensity mode.
  22152. */
  22153. Light.prototype._getPhotometricScale = function () {
  22154. var photometricScale = 0.0;
  22155. var lightTypeID = this.getTypeID();
  22156. //get photometric mode
  22157. var photometricMode = this.intensityMode;
  22158. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22159. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22160. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22161. }
  22162. else {
  22163. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22164. }
  22165. }
  22166. //compute photometric scale
  22167. switch (lightTypeID) {
  22168. case Light.LIGHTTYPEID_POINTLIGHT:
  22169. case Light.LIGHTTYPEID_SPOTLIGHT:
  22170. switch (photometricMode) {
  22171. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22172. photometricScale = 1.0 / (4.0 * Math.PI);
  22173. break;
  22174. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22175. photometricScale = 1.0;
  22176. break;
  22177. case Light.INTENSITYMODE_LUMINANCE:
  22178. photometricScale = this.radius * this.radius;
  22179. break;
  22180. }
  22181. break;
  22182. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22183. switch (photometricMode) {
  22184. case Light.INTENSITYMODE_ILLUMINANCE:
  22185. photometricScale = 1.0;
  22186. break;
  22187. case Light.INTENSITYMODE_LUMINANCE:
  22188. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22189. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22190. var apexAngleRadians = this.radius;
  22191. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22192. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22193. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22194. photometricScale = solidAngle;
  22195. break;
  22196. }
  22197. break;
  22198. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22199. // No fall off in hemisperic light.
  22200. photometricScale = 1.0;
  22201. break;
  22202. }
  22203. return photometricScale;
  22204. };
  22205. /**
  22206. * Reorder the light in the scene according to their defined priority.
  22207. * @hidden Internal Use Only
  22208. */
  22209. Light.prototype._reorderLightsInScene = function () {
  22210. var scene = this.getScene();
  22211. if (this._renderPriority != 0) {
  22212. scene.requireLightSorting = true;
  22213. }
  22214. this.getScene().sortLightsByPriority();
  22215. };
  22216. //lightmapMode Consts
  22217. Light._LIGHTMAP_DEFAULT = 0;
  22218. Light._LIGHTMAP_SPECULAR = 1;
  22219. Light._LIGHTMAP_SHADOWSONLY = 2;
  22220. // Intensity Mode Consts
  22221. Light._INTENSITYMODE_AUTOMATIC = 0;
  22222. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22223. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22224. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22225. Light._INTENSITYMODE_LUMINANCE = 4;
  22226. // Light types ids const.
  22227. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22228. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22229. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22230. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22231. __decorate([
  22232. BABYLON.serializeAsColor3()
  22233. ], Light.prototype, "diffuse", void 0);
  22234. __decorate([
  22235. BABYLON.serializeAsColor3()
  22236. ], Light.prototype, "specular", void 0);
  22237. __decorate([
  22238. BABYLON.serialize()
  22239. ], Light.prototype, "intensity", void 0);
  22240. __decorate([
  22241. BABYLON.serialize()
  22242. ], Light.prototype, "range", void 0);
  22243. __decorate([
  22244. BABYLON.serialize()
  22245. ], Light.prototype, "intensityMode", null);
  22246. __decorate([
  22247. BABYLON.serialize()
  22248. ], Light.prototype, "radius", null);
  22249. __decorate([
  22250. BABYLON.serialize()
  22251. ], Light.prototype, "_renderPriority", void 0);
  22252. __decorate([
  22253. BABYLON.expandToProperty("_reorderLightsInScene")
  22254. ], Light.prototype, "renderPriority", void 0);
  22255. __decorate([
  22256. BABYLON.serialize("shadowEnabled")
  22257. ], Light.prototype, "_shadowEnabled", void 0);
  22258. __decorate([
  22259. BABYLON.serialize("excludeWithLayerMask")
  22260. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22261. __decorate([
  22262. BABYLON.serialize("includeOnlyWithLayerMask")
  22263. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22264. __decorate([
  22265. BABYLON.serialize("lightmapMode")
  22266. ], Light.prototype, "_lightmapMode", void 0);
  22267. return Light;
  22268. }(BABYLON.Node));
  22269. BABYLON.Light = Light;
  22270. })(BABYLON || (BABYLON = {}));
  22271. //# sourceMappingURL=babylon.light.js.map
  22272. var BABYLON;
  22273. (function (BABYLON) {
  22274. var Camera = /** @class */ (function (_super) {
  22275. __extends(Camera, _super);
  22276. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22277. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22278. var _this = _super.call(this, name, scene) || this;
  22279. /**
  22280. * The vector the camera should consider as up.
  22281. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22282. */
  22283. _this.upVector = BABYLON.Vector3.Up();
  22284. _this.orthoLeft = null;
  22285. _this.orthoRight = null;
  22286. _this.orthoBottom = null;
  22287. _this.orthoTop = null;
  22288. /**
  22289. * FOV is set in Radians. (default is 0.8)
  22290. */
  22291. _this.fov = 0.8;
  22292. _this.minZ = 1;
  22293. _this.maxZ = 10000.0;
  22294. _this.inertia = 0.9;
  22295. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22296. _this.isIntermediate = false;
  22297. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22298. /**
  22299. * Restricts the camera to viewing objects with the same layerMask.
  22300. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22301. */
  22302. _this.layerMask = 0x0FFFFFFF;
  22303. /**
  22304. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22305. */
  22306. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22307. // Camera rig members
  22308. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22309. _this._rigCameras = new Array();
  22310. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22311. _this._skipRendering = false;
  22312. _this.customRenderTargets = new Array();
  22313. // Observables
  22314. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22315. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22316. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22317. _this.onRestoreStateObservable = new BABYLON.Observable();
  22318. // Cache
  22319. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22320. _this._projectionMatrix = new BABYLON.Matrix();
  22321. _this._doNotComputeProjectionMatrix = false;
  22322. _this._worldMatrix = BABYLON.Matrix.Identity();
  22323. _this._postProcesses = new Array();
  22324. _this._transformMatrix = BABYLON.Matrix.Zero();
  22325. _this._activeMeshes = new BABYLON.SmartArray(256);
  22326. _this._globalPosition = BABYLON.Vector3.Zero();
  22327. _this._refreshFrustumPlanes = true;
  22328. _this.getScene().addCamera(_this);
  22329. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22330. _this.getScene().activeCamera = _this;
  22331. }
  22332. _this.position = position;
  22333. return _this;
  22334. }
  22335. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22336. get: function () {
  22337. return Camera._PERSPECTIVE_CAMERA;
  22338. },
  22339. enumerable: true,
  22340. configurable: true
  22341. });
  22342. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22343. get: function () {
  22344. return Camera._ORTHOGRAPHIC_CAMERA;
  22345. },
  22346. enumerable: true,
  22347. configurable: true
  22348. });
  22349. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22350. /**
  22351. * This is the default FOV mode for perspective cameras.
  22352. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22353. *
  22354. */
  22355. get: function () {
  22356. return Camera._FOVMODE_VERTICAL_FIXED;
  22357. },
  22358. enumerable: true,
  22359. configurable: true
  22360. });
  22361. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22362. /**
  22363. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22364. *
  22365. */
  22366. get: function () {
  22367. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22368. },
  22369. enumerable: true,
  22370. configurable: true
  22371. });
  22372. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22373. get: function () {
  22374. return Camera._RIG_MODE_NONE;
  22375. },
  22376. enumerable: true,
  22377. configurable: true
  22378. });
  22379. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22380. get: function () {
  22381. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22382. },
  22383. enumerable: true,
  22384. configurable: true
  22385. });
  22386. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22387. get: function () {
  22388. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22389. },
  22390. enumerable: true,
  22391. configurable: true
  22392. });
  22393. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22394. get: function () {
  22395. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22396. },
  22397. enumerable: true,
  22398. configurable: true
  22399. });
  22400. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22401. get: function () {
  22402. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22403. },
  22404. enumerable: true,
  22405. configurable: true
  22406. });
  22407. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22408. get: function () {
  22409. return Camera._RIG_MODE_VR;
  22410. },
  22411. enumerable: true,
  22412. configurable: true
  22413. });
  22414. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22415. get: function () {
  22416. return Camera._RIG_MODE_WEBVR;
  22417. },
  22418. enumerable: true,
  22419. configurable: true
  22420. });
  22421. /**
  22422. * Store current camera state (fov, position, etc..)
  22423. */
  22424. Camera.prototype.storeState = function () {
  22425. this._stateStored = true;
  22426. this._storedFov = this.fov;
  22427. return this;
  22428. };
  22429. /**
  22430. * Restores the camera state values if it has been stored. You must call storeState() first
  22431. */
  22432. Camera.prototype._restoreStateValues = function () {
  22433. if (!this._stateStored) {
  22434. return false;
  22435. }
  22436. this.fov = this._storedFov;
  22437. return true;
  22438. };
  22439. /**
  22440. * Restored camera state. You must call storeState() first
  22441. */
  22442. Camera.prototype.restoreState = function () {
  22443. if (this._restoreStateValues()) {
  22444. this.onRestoreStateObservable.notifyObservers(this);
  22445. return true;
  22446. }
  22447. return false;
  22448. };
  22449. Camera.prototype.getClassName = function () {
  22450. return "Camera";
  22451. };
  22452. /**
  22453. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22454. */
  22455. Camera.prototype.toString = function (fullDetails) {
  22456. var ret = "Name: " + this.name;
  22457. ret += ", type: " + this.getClassName();
  22458. if (this.animations) {
  22459. for (var i = 0; i < this.animations.length; i++) {
  22460. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22461. }
  22462. }
  22463. if (fullDetails) {
  22464. }
  22465. return ret;
  22466. };
  22467. Object.defineProperty(Camera.prototype, "globalPosition", {
  22468. get: function () {
  22469. return this._globalPosition;
  22470. },
  22471. enumerable: true,
  22472. configurable: true
  22473. });
  22474. Camera.prototype.getActiveMeshes = function () {
  22475. return this._activeMeshes;
  22476. };
  22477. Camera.prototype.isActiveMesh = function (mesh) {
  22478. return (this._activeMeshes.indexOf(mesh) !== -1);
  22479. };
  22480. /**
  22481. * Is this camera ready to be used/rendered
  22482. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22483. * @return true if the camera is ready
  22484. */
  22485. Camera.prototype.isReady = function (completeCheck) {
  22486. if (completeCheck === void 0) { completeCheck = false; }
  22487. if (completeCheck) {
  22488. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22489. var pp = _a[_i];
  22490. if (pp && !pp.isReady()) {
  22491. return false;
  22492. }
  22493. }
  22494. }
  22495. return _super.prototype.isReady.call(this, completeCheck);
  22496. };
  22497. //Cache
  22498. Camera.prototype._initCache = function () {
  22499. _super.prototype._initCache.call(this);
  22500. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22501. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22502. this._cache.mode = undefined;
  22503. this._cache.minZ = undefined;
  22504. this._cache.maxZ = undefined;
  22505. this._cache.fov = undefined;
  22506. this._cache.fovMode = undefined;
  22507. this._cache.aspectRatio = undefined;
  22508. this._cache.orthoLeft = undefined;
  22509. this._cache.orthoRight = undefined;
  22510. this._cache.orthoBottom = undefined;
  22511. this._cache.orthoTop = undefined;
  22512. this._cache.renderWidth = undefined;
  22513. this._cache.renderHeight = undefined;
  22514. };
  22515. Camera.prototype._updateCache = function (ignoreParentClass) {
  22516. if (!ignoreParentClass) {
  22517. _super.prototype._updateCache.call(this);
  22518. }
  22519. this._cache.position.copyFrom(this.position);
  22520. this._cache.upVector.copyFrom(this.upVector);
  22521. };
  22522. // Synchronized
  22523. Camera.prototype._isSynchronized = function () {
  22524. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22525. };
  22526. Camera.prototype._isSynchronizedViewMatrix = function () {
  22527. if (!_super.prototype._isSynchronized.call(this))
  22528. return false;
  22529. return this._cache.position.equals(this.position)
  22530. && this._cache.upVector.equals(this.upVector)
  22531. && this.isSynchronizedWithParent();
  22532. };
  22533. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22534. var check = this._cache.mode === this.mode
  22535. && this._cache.minZ === this.minZ
  22536. && this._cache.maxZ === this.maxZ;
  22537. if (!check) {
  22538. return false;
  22539. }
  22540. var engine = this.getEngine();
  22541. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22542. check = this._cache.fov === this.fov
  22543. && this._cache.fovMode === this.fovMode
  22544. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22545. }
  22546. else {
  22547. check = this._cache.orthoLeft === this.orthoLeft
  22548. && this._cache.orthoRight === this.orthoRight
  22549. && this._cache.orthoBottom === this.orthoBottom
  22550. && this._cache.orthoTop === this.orthoTop
  22551. && this._cache.renderWidth === engine.getRenderWidth()
  22552. && this._cache.renderHeight === engine.getRenderHeight();
  22553. }
  22554. return check;
  22555. };
  22556. // Controls
  22557. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22558. };
  22559. Camera.prototype.detachControl = function (element) {
  22560. };
  22561. Camera.prototype.update = function () {
  22562. this._checkInputs();
  22563. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22564. this._updateRigCameras();
  22565. }
  22566. };
  22567. Camera.prototype._checkInputs = function () {
  22568. this.onAfterCheckInputsObservable.notifyObservers(this);
  22569. };
  22570. Object.defineProperty(Camera.prototype, "rigCameras", {
  22571. get: function () {
  22572. return this._rigCameras;
  22573. },
  22574. enumerable: true,
  22575. configurable: true
  22576. });
  22577. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22578. get: function () {
  22579. return this._rigPostProcess;
  22580. },
  22581. enumerable: true,
  22582. configurable: true
  22583. });
  22584. /**
  22585. * Internal, gets the first post proces.
  22586. * @returns the first post process to be run on this camera.
  22587. */
  22588. Camera.prototype._getFirstPostProcess = function () {
  22589. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22590. if (this._postProcesses[ppIndex] !== null) {
  22591. return this._postProcesses[ppIndex];
  22592. }
  22593. }
  22594. return null;
  22595. };
  22596. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22597. // invalidate framebuffer
  22598. var firstPostProcess = this._getFirstPostProcess();
  22599. if (firstPostProcess) {
  22600. firstPostProcess.markTextureDirty();
  22601. }
  22602. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22603. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22604. var cam = this._rigCameras[i];
  22605. var rigPostProcess = cam._rigPostProcess;
  22606. // for VR rig, there does not have to be a post process
  22607. if (rigPostProcess) {
  22608. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22609. if (isPass) {
  22610. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22611. cam.isIntermediate = this._postProcesses.length === 0;
  22612. }
  22613. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22614. rigPostProcess.markTextureDirty();
  22615. }
  22616. else {
  22617. cam._postProcesses = this._postProcesses.slice(0);
  22618. }
  22619. }
  22620. };
  22621. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22622. if (insertAt === void 0) { insertAt = null; }
  22623. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22624. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22625. return 0;
  22626. }
  22627. if (insertAt == null || insertAt < 0) {
  22628. this._postProcesses.push(postProcess);
  22629. }
  22630. else if (this._postProcesses[insertAt] === null) {
  22631. this._postProcesses[insertAt] = postProcess;
  22632. }
  22633. else {
  22634. this._postProcesses.splice(insertAt, 0, postProcess);
  22635. }
  22636. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22637. return this._postProcesses.indexOf(postProcess);
  22638. };
  22639. Camera.prototype.detachPostProcess = function (postProcess) {
  22640. var idx = this._postProcesses.indexOf(postProcess);
  22641. if (idx !== -1) {
  22642. this._postProcesses[idx] = null;
  22643. }
  22644. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22645. };
  22646. Camera.prototype.getWorldMatrix = function () {
  22647. if (this._isSynchronizedViewMatrix()) {
  22648. return this._worldMatrix;
  22649. }
  22650. // Getting the the view matrix will also compute the world matrix.
  22651. this.getViewMatrix();
  22652. return this._worldMatrix;
  22653. };
  22654. Camera.prototype._getViewMatrix = function () {
  22655. return BABYLON.Matrix.Identity();
  22656. };
  22657. Camera.prototype.getViewMatrix = function (force) {
  22658. if (!force && this._isSynchronizedViewMatrix()) {
  22659. return this._computedViewMatrix;
  22660. }
  22661. this.updateCache();
  22662. this._computedViewMatrix = this._getViewMatrix();
  22663. this._currentRenderId = this.getScene().getRenderId();
  22664. this._childRenderId = this._currentRenderId;
  22665. this._refreshFrustumPlanes = true;
  22666. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22667. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22668. }
  22669. this.onViewMatrixChangedObservable.notifyObservers(this);
  22670. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22671. return this._computedViewMatrix;
  22672. };
  22673. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22674. this._doNotComputeProjectionMatrix = true;
  22675. if (projection !== undefined) {
  22676. this._projectionMatrix = projection;
  22677. }
  22678. };
  22679. ;
  22680. Camera.prototype.unfreezeProjectionMatrix = function () {
  22681. this._doNotComputeProjectionMatrix = false;
  22682. };
  22683. ;
  22684. Camera.prototype.getProjectionMatrix = function (force) {
  22685. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22686. return this._projectionMatrix;
  22687. }
  22688. // Cache
  22689. this._cache.mode = this.mode;
  22690. this._cache.minZ = this.minZ;
  22691. this._cache.maxZ = this.maxZ;
  22692. // Matrix
  22693. this._refreshFrustumPlanes = true;
  22694. var engine = this.getEngine();
  22695. var scene = this.getScene();
  22696. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22697. this._cache.fov = this.fov;
  22698. this._cache.fovMode = this.fovMode;
  22699. this._cache.aspectRatio = engine.getAspectRatio(this);
  22700. if (this.minZ <= 0) {
  22701. this.minZ = 0.1;
  22702. }
  22703. if (scene.useRightHandedSystem) {
  22704. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22705. }
  22706. else {
  22707. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22708. }
  22709. }
  22710. else {
  22711. var halfWidth = engine.getRenderWidth() / 2.0;
  22712. var halfHeight = engine.getRenderHeight() / 2.0;
  22713. if (scene.useRightHandedSystem) {
  22714. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22715. }
  22716. else {
  22717. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22718. }
  22719. this._cache.orthoLeft = this.orthoLeft;
  22720. this._cache.orthoRight = this.orthoRight;
  22721. this._cache.orthoBottom = this.orthoBottom;
  22722. this._cache.orthoTop = this.orthoTop;
  22723. this._cache.renderWidth = engine.getRenderWidth();
  22724. this._cache.renderHeight = engine.getRenderHeight();
  22725. }
  22726. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22727. return this._projectionMatrix;
  22728. };
  22729. Camera.prototype.getTranformationMatrix = function () {
  22730. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22731. return this._transformMatrix;
  22732. };
  22733. Camera.prototype.updateFrustumPlanes = function () {
  22734. if (!this._refreshFrustumPlanes) {
  22735. return;
  22736. }
  22737. this.getTranformationMatrix();
  22738. if (!this._frustumPlanes) {
  22739. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22740. }
  22741. else {
  22742. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22743. }
  22744. this._refreshFrustumPlanes = false;
  22745. };
  22746. Camera.prototype.isInFrustum = function (target) {
  22747. this.updateFrustumPlanes();
  22748. return target.isInFrustum(this._frustumPlanes);
  22749. };
  22750. Camera.prototype.isCompletelyInFrustum = function (target) {
  22751. this.updateFrustumPlanes();
  22752. return target.isCompletelyInFrustum(this._frustumPlanes);
  22753. };
  22754. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22755. if (length === void 0) { length = 100; }
  22756. if (!transform) {
  22757. transform = this.getWorldMatrix();
  22758. }
  22759. if (!origin) {
  22760. origin = this.position;
  22761. }
  22762. var forward = new BABYLON.Vector3(0, 0, 1);
  22763. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22764. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22765. return new BABYLON.Ray(origin, direction, length);
  22766. };
  22767. /**
  22768. * Releases resources associated with this node.
  22769. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22770. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22771. */
  22772. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22773. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22774. // Observables
  22775. this.onViewMatrixChangedObservable.clear();
  22776. this.onProjectionMatrixChangedObservable.clear();
  22777. this.onAfterCheckInputsObservable.clear();
  22778. this.onRestoreStateObservable.clear();
  22779. // Inputs
  22780. if (this.inputs) {
  22781. this.inputs.clear();
  22782. }
  22783. // Animations
  22784. this.getScene().stopAnimation(this);
  22785. // Remove from scene
  22786. this.getScene().removeCamera(this);
  22787. while (this._rigCameras.length > 0) {
  22788. var camera = this._rigCameras.pop();
  22789. if (camera) {
  22790. camera.dispose();
  22791. }
  22792. }
  22793. // Postprocesses
  22794. if (this._rigPostProcess) {
  22795. this._rigPostProcess.dispose(this);
  22796. this._rigPostProcess = null;
  22797. this._postProcesses = [];
  22798. }
  22799. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22800. this._rigPostProcess = null;
  22801. this._postProcesses = [];
  22802. }
  22803. else {
  22804. var i = this._postProcesses.length;
  22805. while (--i >= 0) {
  22806. var postProcess = this._postProcesses[i];
  22807. if (postProcess) {
  22808. postProcess.dispose(this);
  22809. }
  22810. }
  22811. }
  22812. // Render targets
  22813. var i = this.customRenderTargets.length;
  22814. while (--i >= 0) {
  22815. this.customRenderTargets[i].dispose();
  22816. }
  22817. this.customRenderTargets = [];
  22818. // Active Meshes
  22819. this._activeMeshes.dispose();
  22820. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22821. };
  22822. Object.defineProperty(Camera.prototype, "leftCamera", {
  22823. // ---- Camera rigs section ----
  22824. get: function () {
  22825. if (this._rigCameras.length < 1) {
  22826. return null;
  22827. }
  22828. return this._rigCameras[0];
  22829. },
  22830. enumerable: true,
  22831. configurable: true
  22832. });
  22833. Object.defineProperty(Camera.prototype, "rightCamera", {
  22834. get: function () {
  22835. if (this._rigCameras.length < 2) {
  22836. return null;
  22837. }
  22838. return this._rigCameras[1];
  22839. },
  22840. enumerable: true,
  22841. configurable: true
  22842. });
  22843. Camera.prototype.getLeftTarget = function () {
  22844. if (this._rigCameras.length < 1) {
  22845. return null;
  22846. }
  22847. return this._rigCameras[0].getTarget();
  22848. };
  22849. Camera.prototype.getRightTarget = function () {
  22850. if (this._rigCameras.length < 2) {
  22851. return null;
  22852. }
  22853. return this._rigCameras[1].getTarget();
  22854. };
  22855. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22856. if (this.cameraRigMode === mode) {
  22857. return;
  22858. }
  22859. while (this._rigCameras.length > 0) {
  22860. var camera = this._rigCameras.pop();
  22861. if (camera) {
  22862. camera.dispose();
  22863. }
  22864. }
  22865. this.cameraRigMode = mode;
  22866. this._cameraRigParams = {};
  22867. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22868. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22869. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22870. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22871. // create the rig cameras, unless none
  22872. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22873. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22874. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22875. if (leftCamera && rightCamera) {
  22876. this._rigCameras.push(leftCamera);
  22877. this._rigCameras.push(rightCamera);
  22878. }
  22879. }
  22880. switch (this.cameraRigMode) {
  22881. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22882. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22883. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22884. break;
  22885. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22886. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22887. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22888. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22889. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22890. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22891. break;
  22892. case Camera.RIG_MODE_VR:
  22893. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22894. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22895. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22896. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22897. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22898. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22899. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22900. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22901. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22902. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22903. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22904. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22905. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22906. if (metrics.compensateDistortion) {
  22907. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22908. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22909. }
  22910. break;
  22911. case Camera.RIG_MODE_WEBVR:
  22912. if (rigParams.vrDisplay) {
  22913. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22914. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22915. //Left eye
  22916. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22917. this._rigCameras[0].setCameraRigParameter("left", true);
  22918. //leaving this for future reference
  22919. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22920. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22921. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22922. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22923. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22924. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22925. this._rigCameras[0].parent = this;
  22926. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22927. //Right eye
  22928. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22929. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22930. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22931. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22932. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22933. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22934. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22935. this._rigCameras[1].parent = this;
  22936. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22937. if (Camera.UseAlternateWebVRRendering) {
  22938. this._rigCameras[1]._skipRendering = true;
  22939. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22940. }
  22941. }
  22942. break;
  22943. }
  22944. this._cascadePostProcessesToRigCams();
  22945. this.update();
  22946. };
  22947. Camera.prototype._getVRProjectionMatrix = function () {
  22948. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22949. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22950. return this._projectionMatrix;
  22951. };
  22952. Camera.prototype._updateCameraRotationMatrix = function () {
  22953. //Here for WebVR
  22954. };
  22955. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22956. //Here for WebVR
  22957. };
  22958. /**
  22959. * This function MUST be overwritten by the different WebVR cameras available.
  22960. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22961. */
  22962. Camera.prototype._getWebVRProjectionMatrix = function () {
  22963. return BABYLON.Matrix.Identity();
  22964. };
  22965. /**
  22966. * This function MUST be overwritten by the different WebVR cameras available.
  22967. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22968. */
  22969. Camera.prototype._getWebVRViewMatrix = function () {
  22970. return BABYLON.Matrix.Identity();
  22971. };
  22972. Camera.prototype.setCameraRigParameter = function (name, value) {
  22973. if (!this._cameraRigParams) {
  22974. this._cameraRigParams = {};
  22975. }
  22976. this._cameraRigParams[name] = value;
  22977. //provisionnally:
  22978. if (name === "interaxialDistance") {
  22979. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22980. }
  22981. };
  22982. /**
  22983. * needs to be overridden by children so sub has required properties to be copied
  22984. */
  22985. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22986. return null;
  22987. };
  22988. /**
  22989. * May need to be overridden by children
  22990. */
  22991. Camera.prototype._updateRigCameras = function () {
  22992. for (var i = 0; i < this._rigCameras.length; i++) {
  22993. this._rigCameras[i].minZ = this.minZ;
  22994. this._rigCameras[i].maxZ = this.maxZ;
  22995. this._rigCameras[i].fov = this.fov;
  22996. }
  22997. // only update viewport when ANAGLYPH
  22998. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22999. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23000. }
  23001. };
  23002. Camera.prototype._setupInputs = function () {
  23003. };
  23004. Camera.prototype.serialize = function () {
  23005. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23006. // Type
  23007. serializationObject.type = this.getClassName();
  23008. // Parent
  23009. if (this.parent) {
  23010. serializationObject.parentId = this.parent.id;
  23011. }
  23012. if (this.inputs) {
  23013. this.inputs.serialize(serializationObject);
  23014. }
  23015. // Animations
  23016. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23017. serializationObject.ranges = this.serializeAnimationRanges();
  23018. return serializationObject;
  23019. };
  23020. Camera.prototype.clone = function (name) {
  23021. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23022. };
  23023. Camera.prototype.getDirection = function (localAxis) {
  23024. var result = BABYLON.Vector3.Zero();
  23025. this.getDirectionToRef(localAxis, result);
  23026. return result;
  23027. };
  23028. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23029. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23030. };
  23031. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23032. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23033. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23034. switch (type) {
  23035. case "ArcRotateCamera":
  23036. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  23037. case "DeviceOrientationCamera":
  23038. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  23039. case "FollowCamera":
  23040. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  23041. case "ArcFollowCamera":
  23042. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  23043. case "GamepadCamera":
  23044. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23045. case "TouchCamera":
  23046. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  23047. case "VirtualJoysticksCamera":
  23048. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  23049. case "WebVRFreeCamera":
  23050. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23051. case "WebVRGamepadCamera":
  23052. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23053. case "VRDeviceOrientationFreeCamera":
  23054. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23055. case "VRDeviceOrientationGamepadCamera":
  23056. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23057. case "AnaglyphArcRotateCamera":
  23058. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23059. case "AnaglyphFreeCamera":
  23060. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23061. case "AnaglyphGamepadCamera":
  23062. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23063. case "AnaglyphUniversalCamera":
  23064. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23065. case "StereoscopicArcRotateCamera":
  23066. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23067. case "StereoscopicFreeCamera":
  23068. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23069. case "StereoscopicGamepadCamera":
  23070. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23071. case "StereoscopicUniversalCamera":
  23072. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23073. case "FreeCamera": // Forcing Universal here
  23074. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23075. default: // Universal Camera is the default value
  23076. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23077. }
  23078. };
  23079. Camera.prototype.computeWorldMatrix = function () {
  23080. return this.getWorldMatrix();
  23081. };
  23082. Camera.Parse = function (parsedCamera, scene) {
  23083. var type = parsedCamera.type;
  23084. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23085. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23086. // Parent
  23087. if (parsedCamera.parentId) {
  23088. camera._waitingParentId = parsedCamera.parentId;
  23089. }
  23090. //If camera has an input manager, let it parse inputs settings
  23091. if (camera.inputs) {
  23092. camera.inputs.parse(parsedCamera);
  23093. camera._setupInputs();
  23094. }
  23095. if (camera.setPosition) { // need to force position
  23096. camera.position.copyFromFloats(0, 0, 0);
  23097. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23098. }
  23099. // Target
  23100. if (parsedCamera.target) {
  23101. if (camera.setTarget) {
  23102. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23103. }
  23104. }
  23105. // Apply 3d rig, when found
  23106. if (parsedCamera.cameraRigMode) {
  23107. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23108. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23109. }
  23110. // Animations
  23111. if (parsedCamera.animations) {
  23112. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23113. var parsedAnimation = parsedCamera.animations[animationIndex];
  23114. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23115. }
  23116. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23117. }
  23118. if (parsedCamera.autoAnimate) {
  23119. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23120. }
  23121. return camera;
  23122. };
  23123. // Statics
  23124. Camera._PERSPECTIVE_CAMERA = 0;
  23125. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23126. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23127. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23128. Camera._RIG_MODE_NONE = 0;
  23129. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23130. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23131. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23132. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23133. Camera._RIG_MODE_VR = 20;
  23134. Camera._RIG_MODE_WEBVR = 21;
  23135. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23136. Camera.UseAlternateWebVRRendering = false;
  23137. __decorate([
  23138. BABYLON.serializeAsVector3()
  23139. ], Camera.prototype, "position", void 0);
  23140. __decorate([
  23141. BABYLON.serializeAsVector3()
  23142. ], Camera.prototype, "upVector", void 0);
  23143. __decorate([
  23144. BABYLON.serialize()
  23145. ], Camera.prototype, "orthoLeft", void 0);
  23146. __decorate([
  23147. BABYLON.serialize()
  23148. ], Camera.prototype, "orthoRight", void 0);
  23149. __decorate([
  23150. BABYLON.serialize()
  23151. ], Camera.prototype, "orthoBottom", void 0);
  23152. __decorate([
  23153. BABYLON.serialize()
  23154. ], Camera.prototype, "orthoTop", void 0);
  23155. __decorate([
  23156. BABYLON.serialize()
  23157. ], Camera.prototype, "fov", void 0);
  23158. __decorate([
  23159. BABYLON.serialize()
  23160. ], Camera.prototype, "minZ", void 0);
  23161. __decorate([
  23162. BABYLON.serialize()
  23163. ], Camera.prototype, "maxZ", void 0);
  23164. __decorate([
  23165. BABYLON.serialize()
  23166. ], Camera.prototype, "inertia", void 0);
  23167. __decorate([
  23168. BABYLON.serialize()
  23169. ], Camera.prototype, "mode", void 0);
  23170. __decorate([
  23171. BABYLON.serialize()
  23172. ], Camera.prototype, "layerMask", void 0);
  23173. __decorate([
  23174. BABYLON.serialize()
  23175. ], Camera.prototype, "fovMode", void 0);
  23176. __decorate([
  23177. BABYLON.serialize()
  23178. ], Camera.prototype, "cameraRigMode", void 0);
  23179. __decorate([
  23180. BABYLON.serialize()
  23181. ], Camera.prototype, "interaxialDistance", void 0);
  23182. __decorate([
  23183. BABYLON.serialize()
  23184. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23185. return Camera;
  23186. }(BABYLON.Node));
  23187. BABYLON.Camera = Camera;
  23188. })(BABYLON || (BABYLON = {}));
  23189. //# sourceMappingURL=babylon.camera.js.map
  23190. var BABYLON;
  23191. (function (BABYLON) {
  23192. var RenderingManager = /** @class */ (function () {
  23193. function RenderingManager(scene) {
  23194. this._renderingGroups = new Array();
  23195. this._autoClearDepthStencil = {};
  23196. this._customOpaqueSortCompareFn = {};
  23197. this._customAlphaTestSortCompareFn = {};
  23198. this._customTransparentSortCompareFn = {};
  23199. this._renderinGroupInfo = null;
  23200. this._scene = scene;
  23201. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23202. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23203. }
  23204. }
  23205. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23206. if (depth === void 0) { depth = true; }
  23207. if (stencil === void 0) { stencil = true; }
  23208. if (this._depthStencilBufferAlreadyCleaned) {
  23209. return;
  23210. }
  23211. this._scene.getEngine().clear(null, false, depth, stencil);
  23212. this._depthStencilBufferAlreadyCleaned = true;
  23213. };
  23214. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23215. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23216. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23217. var info = null;
  23218. if (observable) {
  23219. if (!this._renderinGroupInfo) {
  23220. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23221. }
  23222. info = this._renderinGroupInfo;
  23223. info.scene = this._scene;
  23224. info.camera = this._scene.activeCamera;
  23225. }
  23226. // Dispatch sprites
  23227. if (renderSprites) {
  23228. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23229. var manager = this._scene.spriteManagers[index];
  23230. this.dispatchSprites(manager);
  23231. }
  23232. }
  23233. // Render
  23234. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23235. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23236. var renderingGroup = this._renderingGroups[index];
  23237. if (!renderingGroup && !observable)
  23238. continue;
  23239. var renderingGroupMask = 0;
  23240. // Fire PRECLEAR stage
  23241. if (observable && info) {
  23242. renderingGroupMask = Math.pow(2, index);
  23243. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23244. info.renderingGroupId = index;
  23245. observable.notifyObservers(info, renderingGroupMask);
  23246. }
  23247. // Clear depth/stencil if needed
  23248. if (RenderingManager.AUTOCLEAR) {
  23249. var autoClear = this._autoClearDepthStencil[index];
  23250. if (autoClear && autoClear.autoClear) {
  23251. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23252. }
  23253. }
  23254. if (observable && info) {
  23255. // Fire PREOPAQUE stage
  23256. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23257. observable.notifyObservers(info, renderingGroupMask);
  23258. // Fire PRETRANSPARENT stage
  23259. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23260. observable.notifyObservers(info, renderingGroupMask);
  23261. }
  23262. if (renderingGroup)
  23263. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23264. // Fire POSTTRANSPARENT stage
  23265. if (observable && info) {
  23266. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23267. observable.notifyObservers(info, renderingGroupMask);
  23268. }
  23269. }
  23270. };
  23271. RenderingManager.prototype.reset = function () {
  23272. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23273. var renderingGroup = this._renderingGroups[index];
  23274. if (renderingGroup) {
  23275. renderingGroup.prepare();
  23276. }
  23277. }
  23278. };
  23279. RenderingManager.prototype.dispose = function () {
  23280. this.freeRenderingGroups();
  23281. this._renderingGroups.length = 0;
  23282. };
  23283. /**
  23284. * Clear the info related to rendering groups preventing retention points during dispose.
  23285. */
  23286. RenderingManager.prototype.freeRenderingGroups = function () {
  23287. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23288. var renderingGroup = this._renderingGroups[index];
  23289. if (renderingGroup) {
  23290. renderingGroup.dispose();
  23291. }
  23292. }
  23293. };
  23294. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23295. if (this._renderingGroups[renderingGroupId] === undefined) {
  23296. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23297. }
  23298. };
  23299. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23300. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23301. this._prepareRenderingGroup(renderingGroupId);
  23302. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23303. };
  23304. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23305. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23306. this._prepareRenderingGroup(renderingGroupId);
  23307. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23308. };
  23309. /**
  23310. * @param subMesh The submesh to dispatch
  23311. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23312. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23313. */
  23314. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23315. if (mesh === undefined) {
  23316. mesh = subMesh.getMesh();
  23317. }
  23318. var renderingGroupId = mesh.renderingGroupId || 0;
  23319. this._prepareRenderingGroup(renderingGroupId);
  23320. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23321. };
  23322. /**
  23323. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23324. * This allowed control for front to back rendering or reversly depending of the special needs.
  23325. *
  23326. * @param renderingGroupId The rendering group id corresponding to its index
  23327. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23328. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23329. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23330. */
  23331. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23332. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23333. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23334. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23335. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23336. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23337. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23338. if (this._renderingGroups[renderingGroupId]) {
  23339. var group = this._renderingGroups[renderingGroupId];
  23340. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23341. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23342. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23343. }
  23344. };
  23345. /**
  23346. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23347. *
  23348. * @param renderingGroupId The rendering group id corresponding to its index
  23349. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23350. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23351. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23352. */
  23353. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23354. if (depth === void 0) { depth = true; }
  23355. if (stencil === void 0) { stencil = true; }
  23356. this._autoClearDepthStencil[renderingGroupId] = {
  23357. autoClear: autoClearDepthStencil,
  23358. depth: depth,
  23359. stencil: stencil
  23360. };
  23361. };
  23362. /**
  23363. * The max id used for rendering groups (not included)
  23364. */
  23365. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23366. /**
  23367. * The min id used for rendering groups (included)
  23368. */
  23369. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23370. /**
  23371. * Used to globally prevent autoclearing scenes.
  23372. */
  23373. RenderingManager.AUTOCLEAR = true;
  23374. return RenderingManager;
  23375. }());
  23376. BABYLON.RenderingManager = RenderingManager;
  23377. })(BABYLON || (BABYLON = {}));
  23378. //# sourceMappingURL=babylon.renderingManager.js.map
  23379. var BABYLON;
  23380. (function (BABYLON) {
  23381. var RenderingGroup = /** @class */ (function () {
  23382. /**
  23383. * Creates a new rendering group.
  23384. * @param index The rendering group index
  23385. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23386. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23387. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23388. */
  23389. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23390. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23391. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23392. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23393. this.index = index;
  23394. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23395. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23396. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23397. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23398. this._particleSystems = new BABYLON.SmartArray(256);
  23399. this._spriteManagers = new BABYLON.SmartArray(256);
  23400. this._edgesRenderers = new BABYLON.SmartArray(16);
  23401. this._scene = scene;
  23402. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23403. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23404. this.transparentSortCompareFn = transparentSortCompareFn;
  23405. }
  23406. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23407. /**
  23408. * Set the opaque sort comparison function.
  23409. * If null the sub meshes will be render in the order they were created
  23410. */
  23411. set: function (value) {
  23412. this._opaqueSortCompareFn = value;
  23413. if (value) {
  23414. this._renderOpaque = this.renderOpaqueSorted;
  23415. }
  23416. else {
  23417. this._renderOpaque = RenderingGroup.renderUnsorted;
  23418. }
  23419. },
  23420. enumerable: true,
  23421. configurable: true
  23422. });
  23423. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23424. /**
  23425. * Set the alpha test sort comparison function.
  23426. * If null the sub meshes will be render in the order they were created
  23427. */
  23428. set: function (value) {
  23429. this._alphaTestSortCompareFn = value;
  23430. if (value) {
  23431. this._renderAlphaTest = this.renderAlphaTestSorted;
  23432. }
  23433. else {
  23434. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23435. }
  23436. },
  23437. enumerable: true,
  23438. configurable: true
  23439. });
  23440. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23441. /**
  23442. * Set the transparent sort comparison function.
  23443. * If null the sub meshes will be render in the order they were created
  23444. */
  23445. set: function (value) {
  23446. if (value) {
  23447. this._transparentSortCompareFn = value;
  23448. }
  23449. else {
  23450. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23451. }
  23452. this._renderTransparent = this.renderTransparentSorted;
  23453. },
  23454. enumerable: true,
  23455. configurable: true
  23456. });
  23457. /**
  23458. * Render all the sub meshes contained in the group.
  23459. * @param customRenderFunction Used to override the default render behaviour of the group.
  23460. * @returns true if rendered some submeshes.
  23461. */
  23462. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23463. if (customRenderFunction) {
  23464. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23465. return;
  23466. }
  23467. var engine = this._scene.getEngine();
  23468. // Depth only
  23469. if (this._depthOnlySubMeshes.length !== 0) {
  23470. engine.setColorWrite(false);
  23471. this._renderAlphaTest(this._depthOnlySubMeshes);
  23472. engine.setColorWrite(true);
  23473. }
  23474. // Opaque
  23475. if (this._opaqueSubMeshes.length !== 0) {
  23476. this._renderOpaque(this._opaqueSubMeshes);
  23477. }
  23478. // Alpha test
  23479. if (this._alphaTestSubMeshes.length !== 0) {
  23480. this._renderAlphaTest(this._alphaTestSubMeshes);
  23481. }
  23482. var stencilState = engine.getStencilBuffer();
  23483. engine.setStencilBuffer(false);
  23484. // Sprites
  23485. if (renderSprites) {
  23486. this._renderSprites();
  23487. }
  23488. // Particles
  23489. if (renderParticles) {
  23490. this._renderParticles(activeMeshes);
  23491. }
  23492. if (this.onBeforeTransparentRendering) {
  23493. this.onBeforeTransparentRendering();
  23494. }
  23495. // Transparent
  23496. if (this._transparentSubMeshes.length !== 0) {
  23497. this._renderTransparent(this._transparentSubMeshes);
  23498. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23499. }
  23500. // Set back stencil to false in case it changes before the edge renderer.
  23501. engine.setStencilBuffer(false);
  23502. // Edges
  23503. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23504. this._edgesRenderers.data[edgesRendererIndex].render();
  23505. }
  23506. // Restore Stencil state.
  23507. engine.setStencilBuffer(stencilState);
  23508. };
  23509. /**
  23510. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23511. * @param subMeshes The submeshes to render
  23512. */
  23513. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23514. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23515. };
  23516. /**
  23517. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23518. * @param subMeshes The submeshes to render
  23519. */
  23520. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23521. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23522. };
  23523. /**
  23524. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23525. * @param subMeshes The submeshes to render
  23526. */
  23527. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23528. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23529. };
  23530. /**
  23531. * Renders the submeshes in a specified order.
  23532. * @param subMeshes The submeshes to sort before render
  23533. * @param sortCompareFn The comparison function use to sort
  23534. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23535. * @param transparent Specifies to activate blending if true
  23536. */
  23537. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23538. var subIndex = 0;
  23539. var subMesh;
  23540. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23541. for (; subIndex < subMeshes.length; subIndex++) {
  23542. subMesh = subMeshes.data[subIndex];
  23543. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23544. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23545. }
  23546. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23547. if (sortCompareFn) {
  23548. sortedArray.sort(sortCompareFn);
  23549. }
  23550. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23551. subMesh = sortedArray[subIndex];
  23552. if (transparent) {
  23553. var material = subMesh.getMaterial();
  23554. if (material && material.needDepthPrePass) {
  23555. var engine = material.getScene().getEngine();
  23556. engine.setColorWrite(false);
  23557. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23558. subMesh.render(false);
  23559. engine.setColorWrite(true);
  23560. }
  23561. }
  23562. subMesh.render(transparent);
  23563. }
  23564. };
  23565. /**
  23566. * Renders the submeshes in the order they were dispatched (no sort applied).
  23567. * @param subMeshes The submeshes to render
  23568. */
  23569. RenderingGroup.renderUnsorted = function (subMeshes) {
  23570. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23571. var submesh = subMeshes.data[subIndex];
  23572. submesh.render(false);
  23573. }
  23574. };
  23575. /**
  23576. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23577. * are rendered back to front if in the same alpha index.
  23578. *
  23579. * @param a The first submesh
  23580. * @param b The second submesh
  23581. * @returns The result of the comparison
  23582. */
  23583. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23584. // Alpha index first
  23585. if (a._alphaIndex > b._alphaIndex) {
  23586. return 1;
  23587. }
  23588. if (a._alphaIndex < b._alphaIndex) {
  23589. return -1;
  23590. }
  23591. // Then distance to camera
  23592. return RenderingGroup.backToFrontSortCompare(a, b);
  23593. };
  23594. /**
  23595. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23596. * are rendered back to front.
  23597. *
  23598. * @param a The first submesh
  23599. * @param b The second submesh
  23600. * @returns The result of the comparison
  23601. */
  23602. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23603. // Then distance to camera
  23604. if (a._distanceToCamera < b._distanceToCamera) {
  23605. return 1;
  23606. }
  23607. if (a._distanceToCamera > b._distanceToCamera) {
  23608. return -1;
  23609. }
  23610. return 0;
  23611. };
  23612. /**
  23613. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23614. * are rendered front to back (prevent overdraw).
  23615. *
  23616. * @param a The first submesh
  23617. * @param b The second submesh
  23618. * @returns The result of the comparison
  23619. */
  23620. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23621. // Then distance to camera
  23622. if (a._distanceToCamera < b._distanceToCamera) {
  23623. return -1;
  23624. }
  23625. if (a._distanceToCamera > b._distanceToCamera) {
  23626. return 1;
  23627. }
  23628. return 0;
  23629. };
  23630. /**
  23631. * Resets the different lists of submeshes to prepare a new frame.
  23632. */
  23633. RenderingGroup.prototype.prepare = function () {
  23634. this._opaqueSubMeshes.reset();
  23635. this._transparentSubMeshes.reset();
  23636. this._alphaTestSubMeshes.reset();
  23637. this._depthOnlySubMeshes.reset();
  23638. this._particleSystems.reset();
  23639. this._spriteManagers.reset();
  23640. this._edgesRenderers.reset();
  23641. };
  23642. RenderingGroup.prototype.dispose = function () {
  23643. this._opaqueSubMeshes.dispose();
  23644. this._transparentSubMeshes.dispose();
  23645. this._alphaTestSubMeshes.dispose();
  23646. this._depthOnlySubMeshes.dispose();
  23647. this._particleSystems.dispose();
  23648. this._spriteManagers.dispose();
  23649. this._edgesRenderers.dispose();
  23650. };
  23651. /**
  23652. * Inserts the submesh in its correct queue depending on its material.
  23653. * @param subMesh The submesh to dispatch
  23654. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23655. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23656. */
  23657. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23658. // Get mesh and materials if not provided
  23659. if (mesh === undefined) {
  23660. mesh = subMesh.getMesh();
  23661. }
  23662. if (material === undefined) {
  23663. material = subMesh.getMaterial();
  23664. }
  23665. if (material === null || material === undefined) {
  23666. return;
  23667. }
  23668. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23669. this._transparentSubMeshes.push(subMesh);
  23670. }
  23671. else if (material.needAlphaTesting()) { // Alpha test
  23672. if (material.needDepthPrePass) {
  23673. this._depthOnlySubMeshes.push(subMesh);
  23674. }
  23675. this._alphaTestSubMeshes.push(subMesh);
  23676. }
  23677. else {
  23678. if (material.needDepthPrePass) {
  23679. this._depthOnlySubMeshes.push(subMesh);
  23680. }
  23681. this._opaqueSubMeshes.push(subMesh); // Opaque
  23682. }
  23683. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23684. this._edgesRenderers.push(mesh._edgesRenderer);
  23685. }
  23686. };
  23687. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23688. this._spriteManagers.push(spriteManager);
  23689. };
  23690. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23691. this._particleSystems.push(particleSystem);
  23692. };
  23693. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23694. if (this._particleSystems.length === 0) {
  23695. return;
  23696. }
  23697. // Particles
  23698. var activeCamera = this._scene.activeCamera;
  23699. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23700. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23701. var particleSystem = this._particleSystems.data[particleIndex];
  23702. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23703. continue;
  23704. }
  23705. var emitter = particleSystem.emitter;
  23706. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23707. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23708. }
  23709. }
  23710. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23711. };
  23712. RenderingGroup.prototype._renderSprites = function () {
  23713. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23714. return;
  23715. }
  23716. // Sprites
  23717. var activeCamera = this._scene.activeCamera;
  23718. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23719. for (var id = 0; id < this._spriteManagers.length; id++) {
  23720. var spriteManager = this._spriteManagers.data[id];
  23721. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23722. spriteManager.render();
  23723. }
  23724. }
  23725. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23726. };
  23727. return RenderingGroup;
  23728. }());
  23729. BABYLON.RenderingGroup = RenderingGroup;
  23730. })(BABYLON || (BABYLON = {}));
  23731. //# sourceMappingURL=babylon.renderingGroup.js.map
  23732. var BABYLON;
  23733. (function (BABYLON) {
  23734. /** @hidden */
  23735. var ClickInfo = /** @class */ (function () {
  23736. function ClickInfo() {
  23737. this._singleClick = false;
  23738. this._doubleClick = false;
  23739. this._hasSwiped = false;
  23740. this._ignore = false;
  23741. }
  23742. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23743. get: function () {
  23744. return this._singleClick;
  23745. },
  23746. set: function (b) {
  23747. this._singleClick = b;
  23748. },
  23749. enumerable: true,
  23750. configurable: true
  23751. });
  23752. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23753. get: function () {
  23754. return this._doubleClick;
  23755. },
  23756. set: function (b) {
  23757. this._doubleClick = b;
  23758. },
  23759. enumerable: true,
  23760. configurable: true
  23761. });
  23762. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23763. get: function () {
  23764. return this._hasSwiped;
  23765. },
  23766. set: function (b) {
  23767. this._hasSwiped = b;
  23768. },
  23769. enumerable: true,
  23770. configurable: true
  23771. });
  23772. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23773. get: function () {
  23774. return this._ignore;
  23775. },
  23776. set: function (b) {
  23777. this._ignore = b;
  23778. },
  23779. enumerable: true,
  23780. configurable: true
  23781. });
  23782. return ClickInfo;
  23783. }());
  23784. /**
  23785. * This class is used by the onRenderingGroupObservable
  23786. */
  23787. var RenderingGroupInfo = /** @class */ (function () {
  23788. function RenderingGroupInfo() {
  23789. }
  23790. /**
  23791. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23792. * This stage will be fired no matter what
  23793. */
  23794. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23795. /**
  23796. * Called before opaque object are rendered.
  23797. * This stage will be fired only if there's 3D Opaque content to render
  23798. */
  23799. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23800. /**
  23801. * Called after the opaque objects are rendered and before the transparent ones
  23802. * This stage will be fired only if there's 3D transparent content to render
  23803. */
  23804. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23805. /**
  23806. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23807. * This stage will be fired no matter what
  23808. */
  23809. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23810. return RenderingGroupInfo;
  23811. }());
  23812. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23813. /**
  23814. * Represents a scene to be rendered by the engine.
  23815. * @see http://doc.babylonjs.com/features/scene
  23816. */
  23817. var Scene = /** @class */ (function () {
  23818. /**
  23819. * Creates a new Scene
  23820. * @param engine defines the engine to use to render this scene
  23821. */
  23822. function Scene(engine) {
  23823. // Members
  23824. /**
  23825. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23826. */
  23827. this.autoClear = true;
  23828. /**
  23829. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23830. */
  23831. this.autoClearDepthAndStencil = true;
  23832. /**
  23833. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23834. */
  23835. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23836. /**
  23837. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23838. */
  23839. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23840. this._forceWireframe = false;
  23841. this._forcePointsCloud = false;
  23842. /**
  23843. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23844. */
  23845. this.forceShowBoundingBoxes = false;
  23846. /**
  23847. * Gets or sets a boolean indicating if animations are enabled
  23848. */
  23849. this.animationsEnabled = true;
  23850. this._animationPropertiesOverride = null;
  23851. /**
  23852. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23853. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23854. */
  23855. this.useConstantAnimationDeltaTime = false;
  23856. /**
  23857. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23858. * Please note that it requires to run a ray cast through the scene on every frame
  23859. */
  23860. this.constantlyUpdateMeshUnderPointer = false;
  23861. /**
  23862. * Defines the HTML cursor to use when hovering over interactive elements
  23863. */
  23864. this.hoverCursor = "pointer";
  23865. /**
  23866. * Defines the HTML default cursor to use (empty by default)
  23867. */
  23868. this.defaultCursor = "";
  23869. /**
  23870. * This is used to call preventDefault() on pointer down
  23871. * in order to block unwanted artifacts like system double clicks
  23872. */
  23873. this.preventDefaultOnPointerDown = true;
  23874. // Metadata
  23875. /**
  23876. * Gets or sets user defined metadata
  23877. */
  23878. this.metadata = null;
  23879. /**
  23880. * Use this array to add regular expressions used to disable offline support for specific urls
  23881. */
  23882. this.disableOfflineSupportExceptionRules = new Array();
  23883. /**
  23884. * An event triggered when the scene is disposed.
  23885. */
  23886. this.onDisposeObservable = new BABYLON.Observable();
  23887. this._onDisposeObserver = null;
  23888. /**
  23889. * An event triggered before rendering the scene (right after animations and physics)
  23890. */
  23891. this.onBeforeRenderObservable = new BABYLON.Observable();
  23892. this._onBeforeRenderObserver = null;
  23893. /**
  23894. * An event triggered after rendering the scene
  23895. */
  23896. this.onAfterRenderObservable = new BABYLON.Observable();
  23897. this._onAfterRenderObserver = null;
  23898. /**
  23899. * An event triggered before animating the scene
  23900. */
  23901. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23902. /**
  23903. * An event triggered after animations processing
  23904. */
  23905. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23906. /**
  23907. * An event triggered before draw calls are ready to be sent
  23908. */
  23909. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23910. /**
  23911. * An event triggered after draw calls have been sent
  23912. */
  23913. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23914. /**
  23915. * An event triggered when physic simulation is about to be run
  23916. */
  23917. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23918. /**
  23919. * An event triggered when physic simulation has been done
  23920. */
  23921. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23922. /**
  23923. * An event triggered when the scene is ready
  23924. */
  23925. this.onReadyObservable = new BABYLON.Observable();
  23926. /**
  23927. * An event triggered before rendering a camera
  23928. */
  23929. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23930. this._onBeforeCameraRenderObserver = null;
  23931. /**
  23932. * An event triggered after rendering a camera
  23933. */
  23934. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23935. this._onAfterCameraRenderObserver = null;
  23936. /**
  23937. * An event triggered when active meshes evaluation is about to start
  23938. */
  23939. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23940. /**
  23941. * An event triggered when active meshes evaluation is done
  23942. */
  23943. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23944. /**
  23945. * An event triggered when particles rendering is about to start
  23946. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23947. */
  23948. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23949. /**
  23950. * An event triggered when particles rendering is done
  23951. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23952. */
  23953. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23954. /**
  23955. * An event triggered when sprites rendering is about to start
  23956. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23957. */
  23958. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23959. /**
  23960. * An event triggered when sprites rendering is done
  23961. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23962. */
  23963. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23964. /**
  23965. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23966. */
  23967. this.onDataLoadedObservable = new BABYLON.Observable();
  23968. /**
  23969. * An event triggered when a camera is created
  23970. */
  23971. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23972. /**
  23973. * An event triggered when a camera is removed
  23974. */
  23975. this.onCameraRemovedObservable = new BABYLON.Observable();
  23976. /**
  23977. * An event triggered when a light is created
  23978. */
  23979. this.onNewLightAddedObservable = new BABYLON.Observable();
  23980. /**
  23981. * An event triggered when a light is removed
  23982. */
  23983. this.onLightRemovedObservable = new BABYLON.Observable();
  23984. /**
  23985. * An event triggered when a geometry is created
  23986. */
  23987. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23988. /**
  23989. * An event triggered when a geometry is removed
  23990. */
  23991. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23992. /**
  23993. * An event triggered when a transform node is created
  23994. */
  23995. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23996. /**
  23997. * An event triggered when a transform node is removed
  23998. */
  23999. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24000. /**
  24001. * An event triggered when a mesh is created
  24002. */
  24003. this.onNewMeshAddedObservable = new BABYLON.Observable();
  24004. /**
  24005. * An event triggered when a mesh is removed
  24006. */
  24007. this.onMeshRemovedObservable = new BABYLON.Observable();
  24008. /**
  24009. * An event triggered when render targets are about to be rendered
  24010. * Can happen multiple times per frame.
  24011. */
  24012. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24013. /**
  24014. * An event triggered when render targets were rendered.
  24015. * Can happen multiple times per frame.
  24016. */
  24017. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24018. /**
  24019. * An event triggered before calculating deterministic simulation step
  24020. */
  24021. this.onBeforeStepObservable = new BABYLON.Observable();
  24022. /**
  24023. * An event triggered after calculating deterministic simulation step
  24024. */
  24025. this.onAfterStepObservable = new BABYLON.Observable();
  24026. /**
  24027. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  24028. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24029. * 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)
  24030. */
  24031. this.onRenderingGroupObservable = new BABYLON.Observable();
  24032. // Animations
  24033. /**
  24034. * Gets a list of Animations associated with the scene
  24035. */
  24036. this.animations = [];
  24037. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24038. /**
  24039. * 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).
  24040. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24041. */
  24042. this.onPrePointerObservable = new BABYLON.Observable();
  24043. /**
  24044. * Observable event triggered each time an input event is received from the rendering canvas
  24045. */
  24046. this.onPointerObservable = new BABYLON.Observable();
  24047. this._meshPickProceed = false;
  24048. this._currentPickResult = null;
  24049. this._previousPickResult = null;
  24050. this._totalPointersPressed = 0;
  24051. this._doubleClickOccured = false;
  24052. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24053. this.cameraToUseForPointers = null;
  24054. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24055. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24056. this._startingPointerTime = 0;
  24057. this._previousStartingPointerTime = 0;
  24058. this._pointerCaptures = {};
  24059. // Deterministic lockstep
  24060. this._timeAccumulator = 0;
  24061. this._currentStepId = 0;
  24062. this._currentInternalStep = 0;
  24063. // Keyboard
  24064. /**
  24065. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24066. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24067. */
  24068. this.onPreKeyboardObservable = new BABYLON.Observable();
  24069. /**
  24070. * Observable event triggered each time an keyboard event is received from the hosting window
  24071. */
  24072. this.onKeyboardObservable = new BABYLON.Observable();
  24073. // Coordinates system
  24074. this._useRightHandedSystem = false;
  24075. // Fog
  24076. this._fogEnabled = true;
  24077. this._fogMode = Scene.FOGMODE_NONE;
  24078. /**
  24079. * Gets or sets the fog color to use
  24080. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24081. */
  24082. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24083. /**
  24084. * Gets or sets the fog density to use
  24085. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24086. */
  24087. this.fogDensity = 0.1;
  24088. /**
  24089. * Gets or sets the fog start distance to use
  24090. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24091. */
  24092. this.fogStart = 0;
  24093. /**
  24094. * Gets or sets the fog end distance to use
  24095. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24096. */
  24097. this.fogEnd = 1000.0;
  24098. // Lights
  24099. this._shadowsEnabled = true;
  24100. this._lightsEnabled = true;
  24101. /**
  24102. * All of the lights added to this scene
  24103. * @see http://doc.babylonjs.com/babylon101/lights
  24104. */
  24105. this.lights = new Array();
  24106. // Cameras
  24107. /** All of the cameras added to this scene.
  24108. * @see http://doc.babylonjs.com/babylon101/cameras
  24109. */
  24110. this.cameras = new Array();
  24111. /** All of the active cameras added to this scene. */
  24112. this.activeCameras = new Array();
  24113. // Meshes
  24114. /**
  24115. * All of the tranform nodes added to this scene
  24116. * @see http://doc.babylonjs.com/how_to/transformnode
  24117. */
  24118. this.transformNodes = new Array();
  24119. /**
  24120. * All of the (abstract) meshes added to this scene
  24121. */
  24122. this.meshes = new Array();
  24123. /**
  24124. * All of the animation groups added to this scene
  24125. * @see http://doc.babylonjs.com/how_to/group
  24126. */
  24127. this.animationGroups = new Array();
  24128. // Geometries
  24129. this._geometries = new Array();
  24130. /**
  24131. * All of the materials added to this scene
  24132. * @see http://doc.babylonjs.com/babylon101/materials
  24133. */
  24134. this.materials = new Array();
  24135. /**
  24136. * All of the multi-materials added to this scene
  24137. * @see http://doc.babylonjs.com/how_to/multi_materials
  24138. */
  24139. this.multiMaterials = new Array();
  24140. // Textures
  24141. this._texturesEnabled = true;
  24142. /**
  24143. * All of the textures added to this scene
  24144. */
  24145. this.textures = new Array();
  24146. // Particles
  24147. /**
  24148. * Gets or sets a boolean indicating if particles are enabled on this scene
  24149. */
  24150. this.particlesEnabled = true;
  24151. /**
  24152. * All of the particle systems added to this scene
  24153. * @see http://doc.babylonjs.com/babylon101/particles
  24154. */
  24155. this.particleSystems = new Array();
  24156. // Sprites
  24157. /**
  24158. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24159. */
  24160. this.spritesEnabled = true;
  24161. /**
  24162. * All of the sprite managers added to this scene
  24163. * @see http://doc.babylonjs.com/babylon101/sprites
  24164. */
  24165. this.spriteManagers = new Array();
  24166. /**
  24167. * The list of layers (background and foreground) of the scene
  24168. */
  24169. this.layers = new Array();
  24170. /**
  24171. * The list of effect layers (highlights/glow) added to the scene
  24172. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24173. * @see http://doc.babylonjs.com/how_to/glow_layer
  24174. */
  24175. this.effectLayers = new Array();
  24176. // Skeletons
  24177. this._skeletonsEnabled = true;
  24178. /**
  24179. * The list of skeletons added to the scene
  24180. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24181. */
  24182. this.skeletons = new Array();
  24183. // Morph targets
  24184. /**
  24185. * The list of morph target managers added to the scene
  24186. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24187. */
  24188. this.morphTargetManagers = new Array();
  24189. // Lens flares
  24190. /**
  24191. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24192. */
  24193. this.lensFlaresEnabled = true;
  24194. /**
  24195. * The list of lens flare system added to the scene
  24196. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24197. */
  24198. this.lensFlareSystems = new Array();
  24199. // Collisions
  24200. /**
  24201. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24202. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24203. */
  24204. this.collisionsEnabled = true;
  24205. /**
  24206. * Defines the gravity applied to this scene (used only for collisions)
  24207. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24208. */
  24209. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24210. // Postprocesses
  24211. /**
  24212. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24213. */
  24214. this.postProcessesEnabled = true;
  24215. /**
  24216. * The list of postprocesses added to the scene
  24217. */
  24218. this.postProcesses = new Array();
  24219. // Customs render targets
  24220. /**
  24221. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24222. */
  24223. this.renderTargetsEnabled = true;
  24224. /**
  24225. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24226. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24227. */
  24228. this.dumpNextRenderTargets = false;
  24229. /**
  24230. * The list of user defined render targets added to the scene
  24231. */
  24232. this.customRenderTargets = new Array();
  24233. /**
  24234. * Gets the list of meshes imported to the scene through SceneLoader
  24235. */
  24236. this.importedMeshesFiles = new Array();
  24237. // Probes
  24238. /**
  24239. * Gets or sets a boolean indicating if probes are enabled on this scene
  24240. */
  24241. this.probesEnabled = true;
  24242. /**
  24243. * The list of reflection probes added to the scene
  24244. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24245. */
  24246. this.reflectionProbes = new Array();
  24247. /** @hidden */
  24248. this._actionManagers = new Array();
  24249. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24250. // Procedural textures
  24251. /**
  24252. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24253. */
  24254. this.proceduralTexturesEnabled = true;
  24255. /**
  24256. * The list of procedural textures added to the scene
  24257. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24258. */
  24259. this.proceduralTextures = new Array();
  24260. /**
  24261. * The list of sound tracks added to the scene
  24262. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24263. */
  24264. this.soundTracks = new Array();
  24265. this._audioEnabled = true;
  24266. this._headphone = false;
  24267. // Performance counters
  24268. this._totalVertices = new BABYLON.PerfCounter();
  24269. /** @hidden */
  24270. this._activeIndices = new BABYLON.PerfCounter();
  24271. /** @hidden */
  24272. this._activeParticles = new BABYLON.PerfCounter();
  24273. /** @hidden */
  24274. this._activeBones = new BABYLON.PerfCounter();
  24275. this._animationTime = 0;
  24276. /**
  24277. * Gets or sets a general scale for animation speed
  24278. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24279. */
  24280. this.animationTimeScale = 1;
  24281. this._renderId = 0;
  24282. this._executeWhenReadyTimeoutId = -1;
  24283. this._intermediateRendering = false;
  24284. this._viewUpdateFlag = -1;
  24285. this._projectionUpdateFlag = -1;
  24286. this._alternateViewUpdateFlag = -1;
  24287. this._alternateProjectionUpdateFlag = -1;
  24288. /** @hidden */
  24289. this._toBeDisposed = new BABYLON.SmartArray(256);
  24290. this._activeRequests = new Array();
  24291. this._pendingData = new Array();
  24292. this._isDisposed = false;
  24293. /**
  24294. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24295. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24296. */
  24297. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24298. this._activeMeshes = new BABYLON.SmartArray(256);
  24299. this._processedMaterials = new BABYLON.SmartArray(256);
  24300. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24301. /** @hidden */
  24302. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24303. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24304. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24305. /** @hidden */
  24306. this._activeAnimatables = new Array();
  24307. this._transformMatrix = BABYLON.Matrix.Zero();
  24308. this._useAlternateCameraConfiguration = false;
  24309. this._alternateRendering = false;
  24310. /**
  24311. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24312. * This is useful if there are more lights that the maximum simulteanous authorized
  24313. */
  24314. this.requireLightSorting = false;
  24315. this._depthRenderer = {};
  24316. this._activeMeshesFrozen = false;
  24317. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24318. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24319. this._engine.scenes.push(this);
  24320. this._uid = null;
  24321. this._renderingManager = new BABYLON.RenderingManager(this);
  24322. if (BABYLON.PostProcessManager) {
  24323. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24324. }
  24325. if (BABYLON.OutlineRenderer) {
  24326. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24327. }
  24328. if (BABYLON.Tools.IsWindowObjectExist()) {
  24329. this.attachControl();
  24330. }
  24331. //simplification queue
  24332. if (BABYLON.SimplificationQueue) {
  24333. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24334. }
  24335. //collision coordinator initialization. For now legacy per default.
  24336. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24337. // Uniform Buffer
  24338. this._createUbo();
  24339. // Default Image processing definition
  24340. if (BABYLON.ImageProcessingConfiguration) {
  24341. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24342. }
  24343. }
  24344. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24345. /** The fog is deactivated */
  24346. get: function () {
  24347. return Scene._FOGMODE_NONE;
  24348. },
  24349. enumerable: true,
  24350. configurable: true
  24351. });
  24352. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24353. /** The fog density is following an exponential function */
  24354. get: function () {
  24355. return Scene._FOGMODE_EXP;
  24356. },
  24357. enumerable: true,
  24358. configurable: true
  24359. });
  24360. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24361. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24362. get: function () {
  24363. return Scene._FOGMODE_EXP2;
  24364. },
  24365. enumerable: true,
  24366. configurable: true
  24367. });
  24368. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24369. /** The fog density is following a linear function. */
  24370. get: function () {
  24371. return Scene._FOGMODE_LINEAR;
  24372. },
  24373. enumerable: true,
  24374. configurable: true
  24375. });
  24376. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24377. /**
  24378. * Texture used in all pbr material as the reflection texture.
  24379. * As in the majority of the scene they are the same (exception for multi room and so on),
  24380. * this is easier to reference from here than from all the materials.
  24381. */
  24382. get: function () {
  24383. return this._environmentTexture;
  24384. },
  24385. /**
  24386. * Texture used in all pbr material as the reflection texture.
  24387. * As in the majority of the scene they are the same (exception for multi room and so on),
  24388. * this is easier to set here than in all the materials.
  24389. */
  24390. set: function (value) {
  24391. if (this._environmentTexture === value) {
  24392. return;
  24393. }
  24394. this._environmentTexture = value;
  24395. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24396. },
  24397. enumerable: true,
  24398. configurable: true
  24399. });
  24400. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24401. /**
  24402. * Default image processing configuration used either in the rendering
  24403. * Forward main pass or through the imageProcessingPostProcess if present.
  24404. * As in the majority of the scene they are the same (exception for multi camera),
  24405. * this is easier to reference from here than from all the materials and post process.
  24406. *
  24407. * No setter as we it is a shared configuration, you can set the values instead.
  24408. */
  24409. get: function () {
  24410. return this._imageProcessingConfiguration;
  24411. },
  24412. enumerable: true,
  24413. configurable: true
  24414. });
  24415. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24416. get: function () {
  24417. return this._forceWireframe;
  24418. },
  24419. /**
  24420. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24421. */
  24422. set: function (value) {
  24423. if (this._forceWireframe === value) {
  24424. return;
  24425. }
  24426. this._forceWireframe = value;
  24427. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24428. },
  24429. enumerable: true,
  24430. configurable: true
  24431. });
  24432. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24433. get: function () {
  24434. return this._forcePointsCloud;
  24435. },
  24436. /**
  24437. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24438. */
  24439. set: function (value) {
  24440. if (this._forcePointsCloud === value) {
  24441. return;
  24442. }
  24443. this._forcePointsCloud = value;
  24444. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24445. },
  24446. enumerable: true,
  24447. configurable: true
  24448. });
  24449. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24450. /**
  24451. * Gets or sets the animation properties override
  24452. */
  24453. get: function () {
  24454. return this._animationPropertiesOverride;
  24455. },
  24456. set: function (value) {
  24457. this._animationPropertiesOverride = value;
  24458. },
  24459. enumerable: true,
  24460. configurable: true
  24461. });
  24462. Object.defineProperty(Scene.prototype, "onDispose", {
  24463. /** Sets a function to be executed when this scene is disposed. */
  24464. set: function (callback) {
  24465. if (this._onDisposeObserver) {
  24466. this.onDisposeObservable.remove(this._onDisposeObserver);
  24467. }
  24468. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24469. },
  24470. enumerable: true,
  24471. configurable: true
  24472. });
  24473. Object.defineProperty(Scene.prototype, "beforeRender", {
  24474. /** Sets a function to be executed before rendering this scene */
  24475. set: function (callback) {
  24476. if (this._onBeforeRenderObserver) {
  24477. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24478. }
  24479. if (callback) {
  24480. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24481. }
  24482. },
  24483. enumerable: true,
  24484. configurable: true
  24485. });
  24486. Object.defineProperty(Scene.prototype, "afterRender", {
  24487. /** Sets a function to be executed after rendering this scene */
  24488. set: function (callback) {
  24489. if (this._onAfterRenderObserver) {
  24490. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24491. }
  24492. if (callback) {
  24493. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24494. }
  24495. },
  24496. enumerable: true,
  24497. configurable: true
  24498. });
  24499. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24500. /** Sets a function to be executed before rendering a camera*/
  24501. set: function (callback) {
  24502. if (this._onBeforeCameraRenderObserver) {
  24503. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24504. }
  24505. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24506. },
  24507. enumerable: true,
  24508. configurable: true
  24509. });
  24510. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24511. /** Sets a function to be executed after rendering a camera*/
  24512. set: function (callback) {
  24513. if (this._onAfterCameraRenderObserver) {
  24514. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24515. }
  24516. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24517. },
  24518. enumerable: true,
  24519. configurable: true
  24520. });
  24521. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24522. /**
  24523. * Gets the gamepad manager associated with the scene
  24524. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24525. */
  24526. get: function () {
  24527. if (!this._gamepadManager) {
  24528. this._gamepadManager = new BABYLON.GamepadManager(this);
  24529. }
  24530. return this._gamepadManager;
  24531. },
  24532. enumerable: true,
  24533. configurable: true
  24534. });
  24535. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24536. /**
  24537. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24538. */
  24539. get: function () {
  24540. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24541. },
  24542. enumerable: true,
  24543. configurable: true
  24544. });
  24545. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24546. get: function () {
  24547. return this._useRightHandedSystem;
  24548. },
  24549. /**
  24550. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24551. */
  24552. set: function (value) {
  24553. if (this._useRightHandedSystem === value) {
  24554. return;
  24555. }
  24556. this._useRightHandedSystem = value;
  24557. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24558. },
  24559. enumerable: true,
  24560. configurable: true
  24561. });
  24562. /**
  24563. * Sets the step Id used by deterministic lock step
  24564. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24565. * @param newStepId defines the step Id
  24566. */
  24567. Scene.prototype.setStepId = function (newStepId) {
  24568. this._currentStepId = newStepId;
  24569. };
  24570. ;
  24571. /**
  24572. * Gets the step Id used by deterministic lock step
  24573. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24574. * @returns the step Id
  24575. */
  24576. Scene.prototype.getStepId = function () {
  24577. return this._currentStepId;
  24578. };
  24579. ;
  24580. /**
  24581. * Gets the internal step used by deterministic lock step
  24582. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24583. * @returns the internal step
  24584. */
  24585. Scene.prototype.getInternalStep = function () {
  24586. return this._currentInternalStep;
  24587. };
  24588. ;
  24589. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24590. get: function () {
  24591. return this._fogEnabled;
  24592. },
  24593. /**
  24594. * Gets or sets a boolean indicating if fog is enabled on this scene
  24595. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24596. */
  24597. set: function (value) {
  24598. if (this._fogEnabled === value) {
  24599. return;
  24600. }
  24601. this._fogEnabled = value;
  24602. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24603. },
  24604. enumerable: true,
  24605. configurable: true
  24606. });
  24607. Object.defineProperty(Scene.prototype, "fogMode", {
  24608. get: function () {
  24609. return this._fogMode;
  24610. },
  24611. /**
  24612. * Gets or sets the fog mode to use
  24613. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24614. */
  24615. set: function (value) {
  24616. if (this._fogMode === value) {
  24617. return;
  24618. }
  24619. this._fogMode = value;
  24620. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24621. },
  24622. enumerable: true,
  24623. configurable: true
  24624. });
  24625. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24626. get: function () {
  24627. return this._shadowsEnabled;
  24628. },
  24629. /**
  24630. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24631. */
  24632. set: function (value) {
  24633. if (this._shadowsEnabled === value) {
  24634. return;
  24635. }
  24636. this._shadowsEnabled = value;
  24637. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24638. },
  24639. enumerable: true,
  24640. configurable: true
  24641. });
  24642. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24643. get: function () {
  24644. return this._lightsEnabled;
  24645. },
  24646. /**
  24647. * Gets or sets a boolean indicating if lights are enabled on this scene
  24648. */
  24649. set: function (value) {
  24650. if (this._lightsEnabled === value) {
  24651. return;
  24652. }
  24653. this._lightsEnabled = value;
  24654. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24655. },
  24656. enumerable: true,
  24657. configurable: true
  24658. });
  24659. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24660. /** The default material used on meshes when no material is affected */
  24661. get: function () {
  24662. if (!this._defaultMaterial) {
  24663. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24664. }
  24665. return this._defaultMaterial;
  24666. },
  24667. /** The default material used on meshes when no material is affected */
  24668. set: function (value) {
  24669. this._defaultMaterial = value;
  24670. },
  24671. enumerable: true,
  24672. configurable: true
  24673. });
  24674. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24675. get: function () {
  24676. return this._texturesEnabled;
  24677. },
  24678. /**
  24679. * Gets or sets a boolean indicating if textures are enabled on this scene
  24680. */
  24681. set: function (value) {
  24682. if (this._texturesEnabled === value) {
  24683. return;
  24684. }
  24685. this._texturesEnabled = value;
  24686. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24687. },
  24688. enumerable: true,
  24689. configurable: true
  24690. });
  24691. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24692. get: function () {
  24693. return this._skeletonsEnabled;
  24694. },
  24695. /**
  24696. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24697. */
  24698. set: function (value) {
  24699. if (this._skeletonsEnabled === value) {
  24700. return;
  24701. }
  24702. this._skeletonsEnabled = value;
  24703. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24704. },
  24705. enumerable: true,
  24706. configurable: true
  24707. });
  24708. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24709. /**
  24710. * Gets the postprocess render pipeline manager
  24711. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24712. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24713. */
  24714. get: function () {
  24715. if (!this._postProcessRenderPipelineManager) {
  24716. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24717. }
  24718. return this._postProcessRenderPipelineManager;
  24719. },
  24720. enumerable: true,
  24721. configurable: true
  24722. });
  24723. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24724. /**
  24725. * Gets the main soundtrack associated with the scene
  24726. */
  24727. get: function () {
  24728. if (!this._mainSoundTrack) {
  24729. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24730. }
  24731. return this._mainSoundTrack;
  24732. },
  24733. enumerable: true,
  24734. configurable: true
  24735. });
  24736. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24737. /** @hidden */
  24738. get: function () {
  24739. return this._alternateRendering;
  24740. },
  24741. enumerable: true,
  24742. configurable: true
  24743. });
  24744. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24745. /**
  24746. * Gets the list of frustum planes (built from the active camera)
  24747. */
  24748. get: function () {
  24749. return this._frustumPlanes;
  24750. },
  24751. enumerable: true,
  24752. configurable: true
  24753. });
  24754. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24755. /**
  24756. * Gets the current geometry buffer associated to the scene.
  24757. */
  24758. get: function () {
  24759. return this._geometryBufferRenderer;
  24760. },
  24761. /**
  24762. * Sets the current geometry buffer for the scene.
  24763. */
  24764. set: function (geometryBufferRenderer) {
  24765. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24766. this._geometryBufferRenderer = geometryBufferRenderer;
  24767. }
  24768. },
  24769. enumerable: true,
  24770. configurable: true
  24771. });
  24772. Object.defineProperty(Scene.prototype, "debugLayer", {
  24773. /**
  24774. * Gets the debug layer (aka Inspector) associated with the scene
  24775. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24776. */
  24777. get: function () {
  24778. if (!this._debugLayer) {
  24779. this._debugLayer = new BABYLON.DebugLayer(this);
  24780. }
  24781. return this._debugLayer;
  24782. },
  24783. enumerable: true,
  24784. configurable: true
  24785. });
  24786. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24787. /**
  24788. * Gets a boolean indicating if collisions are processed on a web worker
  24789. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24790. */
  24791. get: function () {
  24792. return this._workerCollisions;
  24793. },
  24794. set: function (enabled) {
  24795. if (!BABYLON.CollisionCoordinatorLegacy) {
  24796. return;
  24797. }
  24798. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24799. this._workerCollisions = enabled;
  24800. if (this.collisionCoordinator) {
  24801. this.collisionCoordinator.destroy();
  24802. }
  24803. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24804. this.collisionCoordinator.init(this);
  24805. },
  24806. enumerable: true,
  24807. configurable: true
  24808. });
  24809. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24810. /**
  24811. * Gets the octree used to boost mesh selection (picking)
  24812. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24813. */
  24814. get: function () {
  24815. return this._selectionOctree;
  24816. },
  24817. enumerable: true,
  24818. configurable: true
  24819. });
  24820. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24821. /**
  24822. * Gets the mesh that is currently under the pointer
  24823. */
  24824. get: function () {
  24825. return this._pointerOverMesh;
  24826. },
  24827. enumerable: true,
  24828. configurable: true
  24829. });
  24830. Object.defineProperty(Scene.prototype, "pointerX", {
  24831. /**
  24832. * Gets the current on-screen X position of the pointer
  24833. */
  24834. get: function () {
  24835. return this._pointerX;
  24836. },
  24837. enumerable: true,
  24838. configurable: true
  24839. });
  24840. Object.defineProperty(Scene.prototype, "pointerY", {
  24841. /**
  24842. * Gets the current on-screen Y position of the pointer
  24843. */
  24844. get: function () {
  24845. return this._pointerY;
  24846. },
  24847. enumerable: true,
  24848. configurable: true
  24849. });
  24850. /**
  24851. * Gets the cached material (ie. the latest rendered one)
  24852. * @returns the cached material
  24853. */
  24854. Scene.prototype.getCachedMaterial = function () {
  24855. return this._cachedMaterial;
  24856. };
  24857. /**
  24858. * Gets the cached effect (ie. the latest rendered one)
  24859. * @returns the cached effect
  24860. */
  24861. Scene.prototype.getCachedEffect = function () {
  24862. return this._cachedEffect;
  24863. };
  24864. /**
  24865. * Gets the cached visibility state (ie. the latest rendered one)
  24866. * @returns the cached visibility state
  24867. */
  24868. Scene.prototype.getCachedVisibility = function () {
  24869. return this._cachedVisibility;
  24870. };
  24871. /**
  24872. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24873. * @param material defines the current material
  24874. * @param effect defines the current effect
  24875. * @param visibility defines the current visibility state
  24876. * @returns true if one parameter is not cached
  24877. */
  24878. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24879. if (visibility === void 0) { visibility = 1; }
  24880. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24881. };
  24882. /**
  24883. * Gets the bounding box renderer associated with the scene
  24884. * @returns a BoundingBoxRenderer
  24885. */
  24886. Scene.prototype.getBoundingBoxRenderer = function () {
  24887. if (!this._boundingBoxRenderer) {
  24888. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24889. }
  24890. return this._boundingBoxRenderer;
  24891. };
  24892. /**
  24893. * Gets the outline renderer associated with the scene
  24894. * @returns a OutlineRenderer
  24895. */
  24896. Scene.prototype.getOutlineRenderer = function () {
  24897. return this._outlineRenderer;
  24898. };
  24899. /**
  24900. * Gets the engine associated with the scene
  24901. * @returns an Engine
  24902. */
  24903. Scene.prototype.getEngine = function () {
  24904. return this._engine;
  24905. };
  24906. /**
  24907. * Gets the total number of vertices rendered per frame
  24908. * @returns the total number of vertices rendered per frame
  24909. */
  24910. Scene.prototype.getTotalVertices = function () {
  24911. return this._totalVertices.current;
  24912. };
  24913. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24914. /**
  24915. * Gets the performance counter for total vertices
  24916. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24917. */
  24918. get: function () {
  24919. return this._totalVertices;
  24920. },
  24921. enumerable: true,
  24922. configurable: true
  24923. });
  24924. /**
  24925. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24926. * @returns the total number of active indices rendered per frame
  24927. */
  24928. Scene.prototype.getActiveIndices = function () {
  24929. return this._activeIndices.current;
  24930. };
  24931. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24932. /**
  24933. * Gets the performance counter for active indices
  24934. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24935. */
  24936. get: function () {
  24937. return this._activeIndices;
  24938. },
  24939. enumerable: true,
  24940. configurable: true
  24941. });
  24942. /**
  24943. * Gets the total number of active particles rendered per frame
  24944. * @returns the total number of active particles rendered per frame
  24945. */
  24946. Scene.prototype.getActiveParticles = function () {
  24947. return this._activeParticles.current;
  24948. };
  24949. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24950. /**
  24951. * Gets the performance counter for active particles
  24952. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24953. */
  24954. get: function () {
  24955. return this._activeParticles;
  24956. },
  24957. enumerable: true,
  24958. configurable: true
  24959. });
  24960. /**
  24961. * Gets the total number of active bones rendered per frame
  24962. * @returns the total number of active bones rendered per frame
  24963. */
  24964. Scene.prototype.getActiveBones = function () {
  24965. return this._activeBones.current;
  24966. };
  24967. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24968. /**
  24969. * Gets the performance counter for active bones
  24970. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24971. */
  24972. get: function () {
  24973. return this._activeBones;
  24974. },
  24975. enumerable: true,
  24976. configurable: true
  24977. });
  24978. /** @hidden */
  24979. Scene.prototype.getInterFramePerfCounter = function () {
  24980. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24981. return 0;
  24982. };
  24983. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24984. /** @hidden */
  24985. get: function () {
  24986. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24987. return null;
  24988. },
  24989. enumerable: true,
  24990. configurable: true
  24991. });
  24992. /** @hidden */
  24993. Scene.prototype.getLastFrameDuration = function () {
  24994. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24995. return 0;
  24996. };
  24997. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24998. /** @hidden */
  24999. get: function () {
  25000. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25001. return null;
  25002. },
  25003. enumerable: true,
  25004. configurable: true
  25005. });
  25006. /** @hidden */
  25007. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25008. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25009. return 0;
  25010. };
  25011. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25012. /** @hidden */
  25013. get: function () {
  25014. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25015. return null;
  25016. },
  25017. enumerable: true,
  25018. configurable: true
  25019. });
  25020. /**
  25021. * Gets the array of active meshes
  25022. * @returns an array of AbstractMesh
  25023. */
  25024. Scene.prototype.getActiveMeshes = function () {
  25025. return this._activeMeshes;
  25026. };
  25027. /** @hidden */
  25028. Scene.prototype.getRenderTargetsDuration = function () {
  25029. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25030. return 0;
  25031. };
  25032. /** @hidden */
  25033. Scene.prototype.getRenderDuration = function () {
  25034. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25035. return 0;
  25036. };
  25037. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25038. /** @hidden */
  25039. get: function () {
  25040. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25041. return null;
  25042. },
  25043. enumerable: true,
  25044. configurable: true
  25045. });
  25046. /** @hidden */
  25047. Scene.prototype.getParticlesDuration = function () {
  25048. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25049. return 0;
  25050. };
  25051. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25052. /** @hidden */
  25053. get: function () {
  25054. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25055. return null;
  25056. },
  25057. enumerable: true,
  25058. configurable: true
  25059. });
  25060. /** @hidden */
  25061. Scene.prototype.getSpritesDuration = function () {
  25062. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25063. return 0;
  25064. };
  25065. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25066. /** @hidden */
  25067. get: function () {
  25068. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25069. return null;
  25070. },
  25071. enumerable: true,
  25072. configurable: true
  25073. });
  25074. /**
  25075. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25076. * @returns a number
  25077. */
  25078. Scene.prototype.getAnimationRatio = function () {
  25079. return this._animationRatio;
  25080. };
  25081. /**
  25082. * Gets an unique Id for the current frame
  25083. * @returns a number
  25084. */
  25085. Scene.prototype.getRenderId = function () {
  25086. return this._renderId;
  25087. };
  25088. /** Call this function if you want to manually increment the render Id*/
  25089. Scene.prototype.incrementRenderId = function () {
  25090. this._renderId++;
  25091. };
  25092. Scene.prototype._updatePointerPosition = function (evt) {
  25093. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25094. if (!canvasRect) {
  25095. return;
  25096. }
  25097. this._pointerX = evt.clientX - canvasRect.left;
  25098. this._pointerY = evt.clientY - canvasRect.top;
  25099. this._unTranslatedPointerX = this._pointerX;
  25100. this._unTranslatedPointerY = this._pointerY;
  25101. };
  25102. Scene.prototype._createUbo = function () {
  25103. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25104. this._sceneUbo.addUniform("viewProjection", 16);
  25105. this._sceneUbo.addUniform("view", 16);
  25106. };
  25107. Scene.prototype._createAlternateUbo = function () {
  25108. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25109. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25110. this._alternateSceneUbo.addUniform("view", 16);
  25111. };
  25112. // Pointers handling
  25113. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25114. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25115. if (result) {
  25116. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25117. }
  25118. return result;
  25119. };
  25120. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25121. if (pointerInfo.pickInfo) {
  25122. if (!pointerInfo.pickInfo.ray) {
  25123. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25124. }
  25125. }
  25126. };
  25127. /**
  25128. * Use this method to simulate a pointer move on a mesh
  25129. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25130. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25131. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25132. * @returns the current scene
  25133. */
  25134. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25135. var evt = new PointerEvent("pointermove", pointerEventInit);
  25136. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25137. return this;
  25138. }
  25139. return this._processPointerMove(pickResult, evt);
  25140. };
  25141. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25142. var canvas = this._engine.getRenderingCanvas();
  25143. if (!canvas) {
  25144. return this;
  25145. }
  25146. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25147. this.setPointerOverSprite(null);
  25148. this.setPointerOverMesh(pickResult.pickedMesh);
  25149. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25150. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25151. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25152. }
  25153. else {
  25154. canvas.style.cursor = this.hoverCursor;
  25155. }
  25156. }
  25157. else {
  25158. canvas.style.cursor = this.defaultCursor;
  25159. }
  25160. }
  25161. else {
  25162. this.setPointerOverMesh(null);
  25163. // Sprites
  25164. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25165. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25166. this.setPointerOverSprite(pickResult.pickedSprite);
  25167. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25168. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25169. }
  25170. else {
  25171. canvas.style.cursor = this.hoverCursor;
  25172. }
  25173. }
  25174. else {
  25175. this.setPointerOverSprite(null);
  25176. // Restore pointer
  25177. canvas.style.cursor = this.defaultCursor;
  25178. }
  25179. }
  25180. if (pickResult) {
  25181. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25182. if (this.onPointerMove) {
  25183. this.onPointerMove(evt, pickResult, type);
  25184. }
  25185. if (this.onPointerObservable.hasObservers()) {
  25186. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25187. this._setRayOnPointerInfo(pi);
  25188. this.onPointerObservable.notifyObservers(pi, type);
  25189. }
  25190. }
  25191. return this;
  25192. };
  25193. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25194. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25195. if (pickResult) {
  25196. pi.ray = pickResult.ray;
  25197. }
  25198. this.onPrePointerObservable.notifyObservers(pi, type);
  25199. if (pi.skipOnPointerObservable) {
  25200. return true;
  25201. }
  25202. else {
  25203. return false;
  25204. }
  25205. };
  25206. /**
  25207. * Use this method to simulate a pointer down on a mesh
  25208. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25209. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25210. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25211. * @returns the current scene
  25212. */
  25213. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25214. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25215. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25216. return this;
  25217. }
  25218. return this._processPointerDown(pickResult, evt);
  25219. };
  25220. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25221. var _this = this;
  25222. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25223. this._pickedDownMesh = pickResult.pickedMesh;
  25224. var actionManager = pickResult.pickedMesh.actionManager;
  25225. if (actionManager) {
  25226. if (actionManager.hasPickTriggers) {
  25227. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25228. switch (evt.button) {
  25229. case 0:
  25230. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25231. break;
  25232. case 1:
  25233. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25234. break;
  25235. case 2:
  25236. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25237. break;
  25238. }
  25239. }
  25240. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25241. window.setTimeout(function () {
  25242. 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);
  25243. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25244. if (_this._totalPointersPressed !== 0 &&
  25245. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25246. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25247. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25248. _this._startingPointerTime = 0;
  25249. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25250. }
  25251. }
  25252. }, Scene.LongPressDelay);
  25253. }
  25254. }
  25255. }
  25256. if (pickResult) {
  25257. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25258. if (this.onPointerDown) {
  25259. this.onPointerDown(evt, pickResult, type);
  25260. }
  25261. if (this.onPointerObservable.hasObservers()) {
  25262. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25263. this._setRayOnPointerInfo(pi);
  25264. this.onPointerObservable.notifyObservers(pi, type);
  25265. }
  25266. }
  25267. return this;
  25268. };
  25269. /**
  25270. * Use this method to simulate a pointer up on a mesh
  25271. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25272. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25273. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25274. * @returns the current scene
  25275. */
  25276. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25277. var evt = new PointerEvent("pointerup", pointerEventInit);
  25278. var clickInfo = new ClickInfo();
  25279. clickInfo.singleClick = true;
  25280. clickInfo.ignore = true;
  25281. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25282. return this;
  25283. }
  25284. return this._processPointerUp(pickResult, evt, clickInfo);
  25285. };
  25286. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25287. if (pickResult && pickResult && pickResult.pickedMesh) {
  25288. this._pickedUpMesh = pickResult.pickedMesh;
  25289. if (this._pickedDownMesh === this._pickedUpMesh) {
  25290. if (this.onPointerPick) {
  25291. this.onPointerPick(evt, pickResult);
  25292. }
  25293. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25294. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25295. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25296. this._setRayOnPointerInfo(pi);
  25297. this.onPointerObservable.notifyObservers(pi, type_1);
  25298. }
  25299. }
  25300. if (pickResult.pickedMesh.actionManager) {
  25301. if (clickInfo.ignore) {
  25302. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25303. }
  25304. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25305. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25306. }
  25307. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25308. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25309. }
  25310. }
  25311. }
  25312. if (this._pickedDownMesh &&
  25313. this._pickedDownMesh.actionManager &&
  25314. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25315. this._pickedDownMesh !== this._pickedUpMesh) {
  25316. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25317. }
  25318. var type = BABYLON.PointerEventTypes.POINTERUP;
  25319. if (this.onPointerObservable.hasObservers()) {
  25320. if (!clickInfo.ignore) {
  25321. if (!clickInfo.hasSwiped) {
  25322. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25323. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25324. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25325. this._setRayOnPointerInfo(pi);
  25326. this.onPointerObservable.notifyObservers(pi, type_2);
  25327. }
  25328. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25329. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25330. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25331. this._setRayOnPointerInfo(pi);
  25332. this.onPointerObservable.notifyObservers(pi, type_3);
  25333. }
  25334. }
  25335. }
  25336. else {
  25337. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25338. this._setRayOnPointerInfo(pi);
  25339. this.onPointerObservable.notifyObservers(pi, type);
  25340. }
  25341. }
  25342. if (this.onPointerUp) {
  25343. this.onPointerUp(evt, pickResult, type);
  25344. }
  25345. return this;
  25346. };
  25347. /**
  25348. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25349. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25350. * @returns true if the pointer was captured
  25351. */
  25352. Scene.prototype.isPointerCaptured = function (pointerId) {
  25353. if (pointerId === void 0) { pointerId = 0; }
  25354. return this._pointerCaptures[pointerId];
  25355. };
  25356. /**
  25357. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25358. * @param attachUp defines if you want to attach events to pointerup
  25359. * @param attachDown defines if you want to attach events to pointerdown
  25360. * @param attachMove defines if you want to attach events to pointermove
  25361. */
  25362. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25363. var _this = this;
  25364. if (attachUp === void 0) { attachUp = true; }
  25365. if (attachDown === void 0) { attachDown = true; }
  25366. if (attachMove === void 0) { attachMove = true; }
  25367. this._initActionManager = function (act, clickInfo) {
  25368. if (!_this._meshPickProceed) {
  25369. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25370. _this._currentPickResult = pickResult;
  25371. if (pickResult) {
  25372. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25373. }
  25374. _this._meshPickProceed = true;
  25375. }
  25376. return act;
  25377. };
  25378. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25379. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25380. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25381. btn !== _this._previousButtonPressed) {
  25382. _this._doubleClickOccured = false;
  25383. clickInfo.singleClick = true;
  25384. clickInfo.ignore = false;
  25385. cb(clickInfo, _this._currentPickResult);
  25386. }
  25387. };
  25388. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25389. var clickInfo = new ClickInfo();
  25390. _this._currentPickResult = null;
  25391. var act = null;
  25392. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25393. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25394. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25395. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25396. act = _this._initActionManager(act, clickInfo);
  25397. if (act)
  25398. checkPicking = act.hasPickTriggers;
  25399. }
  25400. if (checkPicking) {
  25401. var btn = evt.button;
  25402. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25403. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25404. if (!clickInfo.hasSwiped) {
  25405. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25406. if (!checkSingleClickImmediately) {
  25407. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25408. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25409. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25410. act = _this._initActionManager(act, clickInfo);
  25411. if (act)
  25412. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25413. }
  25414. }
  25415. if (checkSingleClickImmediately) {
  25416. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25417. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25418. btn !== _this._previousButtonPressed) {
  25419. clickInfo.singleClick = true;
  25420. cb(clickInfo, _this._currentPickResult);
  25421. }
  25422. }
  25423. // at least one double click is required to be check and exclusive double click is enabled
  25424. else {
  25425. // wait that no double click has been raised during the double click delay
  25426. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25427. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25428. }
  25429. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25430. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25431. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25432. act = _this._initActionManager(act, clickInfo);
  25433. if (act)
  25434. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25435. }
  25436. if (checkDoubleClick) {
  25437. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25438. if (btn === _this._previousButtonPressed &&
  25439. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25440. !_this._doubleClickOccured) {
  25441. // pointer has not moved for 2 clicks, it's a double click
  25442. if (!clickInfo.hasSwiped &&
  25443. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25444. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25445. _this._previousStartingPointerTime = 0;
  25446. _this._doubleClickOccured = true;
  25447. clickInfo.doubleClick = true;
  25448. clickInfo.ignore = false;
  25449. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25450. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25451. }
  25452. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25453. cb(clickInfo, _this._currentPickResult);
  25454. }
  25455. // if the two successive clicks are too far, it's just two simple clicks
  25456. else {
  25457. _this._doubleClickOccured = false;
  25458. _this._previousStartingPointerTime = _this._startingPointerTime;
  25459. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25460. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25461. _this._previousButtonPressed = btn;
  25462. if (Scene.ExclusiveDoubleClickMode) {
  25463. if (_this._previousDelayedSimpleClickTimeout) {
  25464. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25465. }
  25466. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25467. cb(clickInfo, _this._previousPickResult);
  25468. }
  25469. else {
  25470. cb(clickInfo, _this._currentPickResult);
  25471. }
  25472. }
  25473. }
  25474. // just the first click of the double has been raised
  25475. else {
  25476. _this._doubleClickOccured = false;
  25477. _this._previousStartingPointerTime = _this._startingPointerTime;
  25478. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25479. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25480. _this._previousButtonPressed = btn;
  25481. }
  25482. }
  25483. }
  25484. }
  25485. clickInfo.ignore = true;
  25486. cb(clickInfo, _this._currentPickResult);
  25487. };
  25488. this._spritePredicate = function (sprite) {
  25489. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25490. };
  25491. this._onPointerMove = function (evt) {
  25492. _this._updatePointerPosition(evt);
  25493. // PreObservable support
  25494. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25495. return;
  25496. }
  25497. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25498. return;
  25499. }
  25500. if (!_this.pointerMovePredicate) {
  25501. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25502. }
  25503. // Meshes
  25504. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25505. _this._processPointerMove(pickResult, evt);
  25506. };
  25507. this._onPointerDown = function (evt) {
  25508. _this._totalPointersPressed++;
  25509. _this._pickedDownMesh = null;
  25510. _this._meshPickProceed = false;
  25511. _this._updatePointerPosition(evt);
  25512. if (_this.preventDefaultOnPointerDown && canvas) {
  25513. evt.preventDefault();
  25514. canvas.focus();
  25515. }
  25516. // PreObservable support
  25517. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25518. return;
  25519. }
  25520. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25521. return;
  25522. }
  25523. _this._pointerCaptures[evt.pointerId] = true;
  25524. _this._startingPointerPosition.x = _this._pointerX;
  25525. _this._startingPointerPosition.y = _this._pointerY;
  25526. _this._startingPointerTime = Date.now();
  25527. if (!_this.pointerDownPredicate) {
  25528. _this.pointerDownPredicate = function (mesh) {
  25529. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25530. };
  25531. }
  25532. // Meshes
  25533. _this._pickedDownMesh = null;
  25534. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25535. _this._processPointerDown(pickResult, evt);
  25536. // Sprites
  25537. _this._pickedDownSprite = null;
  25538. if (_this.spriteManagers.length > 0) {
  25539. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25540. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25541. if (pickResult.pickedSprite.actionManager) {
  25542. _this._pickedDownSprite = pickResult.pickedSprite;
  25543. switch (evt.button) {
  25544. case 0:
  25545. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25546. break;
  25547. case 1:
  25548. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25549. break;
  25550. case 2:
  25551. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25552. break;
  25553. }
  25554. if (pickResult.pickedSprite.actionManager) {
  25555. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25556. }
  25557. }
  25558. }
  25559. }
  25560. };
  25561. this._onPointerUp = function (evt) {
  25562. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25563. return; // So we need to test it the pointer down was pressed before.
  25564. }
  25565. _this._totalPointersPressed--;
  25566. _this._pickedUpMesh = null;
  25567. _this._meshPickProceed = false;
  25568. _this._updatePointerPosition(evt);
  25569. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25570. // PreObservable support
  25571. if (_this.onPrePointerObservable.hasObservers()) {
  25572. if (!clickInfo.ignore) {
  25573. if (!clickInfo.hasSwiped) {
  25574. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25575. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25576. return;
  25577. }
  25578. }
  25579. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25580. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25581. return;
  25582. }
  25583. }
  25584. }
  25585. }
  25586. else {
  25587. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25588. return;
  25589. }
  25590. }
  25591. }
  25592. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25593. return;
  25594. }
  25595. _this._pointerCaptures[evt.pointerId] = false;
  25596. if (!_this.pointerUpPredicate) {
  25597. _this.pointerUpPredicate = function (mesh) {
  25598. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25599. };
  25600. }
  25601. // Meshes
  25602. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25603. _this._initActionManager(null, clickInfo);
  25604. }
  25605. if (!pickResult) {
  25606. pickResult = _this._currentPickResult;
  25607. }
  25608. _this._processPointerUp(pickResult, evt, clickInfo);
  25609. // Sprites
  25610. if (!clickInfo.ignore) {
  25611. if (_this.spriteManagers.length > 0) {
  25612. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25613. if (spritePickResult) {
  25614. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25615. if (spritePickResult.pickedSprite.actionManager) {
  25616. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25617. if (spritePickResult.pickedSprite.actionManager) {
  25618. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25619. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25620. }
  25621. }
  25622. }
  25623. }
  25624. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25625. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25626. }
  25627. }
  25628. }
  25629. }
  25630. _this._previousPickResult = _this._currentPickResult;
  25631. });
  25632. };
  25633. this._onKeyDown = function (evt) {
  25634. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25635. if (_this.onPreKeyboardObservable.hasObservers()) {
  25636. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25637. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25638. if (pi.skipOnPointerObservable) {
  25639. return;
  25640. }
  25641. }
  25642. if (_this.onKeyboardObservable.hasObservers()) {
  25643. var pi = new BABYLON.KeyboardInfo(type, evt);
  25644. _this.onKeyboardObservable.notifyObservers(pi, type);
  25645. }
  25646. if (_this.actionManager) {
  25647. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25648. }
  25649. };
  25650. this._onKeyUp = function (evt) {
  25651. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25652. if (_this.onPreKeyboardObservable.hasObservers()) {
  25653. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25654. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25655. if (pi.skipOnPointerObservable) {
  25656. return;
  25657. }
  25658. }
  25659. if (_this.onKeyboardObservable.hasObservers()) {
  25660. var pi = new BABYLON.KeyboardInfo(type, evt);
  25661. _this.onKeyboardObservable.notifyObservers(pi, type);
  25662. }
  25663. if (_this.actionManager) {
  25664. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25665. }
  25666. };
  25667. var engine = this.getEngine();
  25668. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25669. if (!canvas) {
  25670. return;
  25671. }
  25672. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25673. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25674. });
  25675. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25676. if (!canvas) {
  25677. return;
  25678. }
  25679. canvas.removeEventListener("keydown", _this._onKeyDown);
  25680. canvas.removeEventListener("keyup", _this._onKeyUp);
  25681. });
  25682. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25683. var canvas = this._engine.getRenderingCanvas();
  25684. if (!canvas) {
  25685. return;
  25686. }
  25687. if (attachMove) {
  25688. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25689. // Wheel
  25690. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25691. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25692. }
  25693. if (attachDown) {
  25694. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25695. }
  25696. if (attachUp) {
  25697. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25698. }
  25699. canvas.tabIndex = 1;
  25700. };
  25701. /** Detaches all event handlers*/
  25702. Scene.prototype.detachControl = function () {
  25703. var engine = this.getEngine();
  25704. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25705. var canvas = engine.getRenderingCanvas();
  25706. if (!canvas) {
  25707. return;
  25708. }
  25709. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25710. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25711. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25712. if (this._onCanvasBlurObserver) {
  25713. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25714. }
  25715. if (this._onCanvasFocusObserver) {
  25716. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25717. }
  25718. // Wheel
  25719. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25720. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25721. // Keyboard
  25722. canvas.removeEventListener("keydown", this._onKeyDown);
  25723. canvas.removeEventListener("keyup", this._onKeyUp);
  25724. // Observables
  25725. this.onKeyboardObservable.clear();
  25726. this.onPreKeyboardObservable.clear();
  25727. this.onPointerObservable.clear();
  25728. this.onPrePointerObservable.clear();
  25729. };
  25730. /**
  25731. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25732. * Delay loaded resources are not taking in account
  25733. * @return true if all required resources are ready
  25734. */
  25735. Scene.prototype.isReady = function () {
  25736. if (this._isDisposed) {
  25737. return false;
  25738. }
  25739. if (this._pendingData.length > 0) {
  25740. return false;
  25741. }
  25742. var index;
  25743. var engine = this.getEngine();
  25744. // Geometries
  25745. for (index = 0; index < this._geometries.length; index++) {
  25746. var geometry = this._geometries[index];
  25747. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25748. return false;
  25749. }
  25750. }
  25751. // Meshes
  25752. for (index = 0; index < this.meshes.length; index++) {
  25753. var mesh = this.meshes[index];
  25754. if (!mesh.isEnabled()) {
  25755. continue;
  25756. }
  25757. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25758. continue;
  25759. }
  25760. if (!mesh.isReady(true)) {
  25761. return false;
  25762. }
  25763. // Effect layers
  25764. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25765. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25766. var layer = _a[_i];
  25767. if (!layer.hasMesh(mesh)) {
  25768. continue;
  25769. }
  25770. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25771. var subMesh = _c[_b];
  25772. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25773. return false;
  25774. }
  25775. }
  25776. }
  25777. }
  25778. // Post-processes
  25779. if (this.activeCameras && this.activeCameras.length > 0) {
  25780. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25781. var camera = _e[_d];
  25782. if (!camera.isReady(true)) {
  25783. return false;
  25784. }
  25785. }
  25786. }
  25787. else if (this.activeCamera) {
  25788. if (!this.activeCamera.isReady(true)) {
  25789. return false;
  25790. }
  25791. }
  25792. // Particles
  25793. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25794. var particleSystem = _g[_f];
  25795. if (!particleSystem.isReady()) {
  25796. return false;
  25797. }
  25798. }
  25799. return true;
  25800. };
  25801. /** Resets all cached information relative to material (including effect and visibility) */
  25802. Scene.prototype.resetCachedMaterial = function () {
  25803. this._cachedMaterial = null;
  25804. this._cachedEffect = null;
  25805. this._cachedVisibility = null;
  25806. };
  25807. /**
  25808. * Registers a function to be called before every frame render
  25809. * @param func defines the function to register
  25810. */
  25811. Scene.prototype.registerBeforeRender = function (func) {
  25812. this.onBeforeRenderObservable.add(func);
  25813. };
  25814. /**
  25815. * Unregisters a function called before every frame render
  25816. * @param func defines the function to unregister
  25817. */
  25818. Scene.prototype.unregisterBeforeRender = function (func) {
  25819. this.onBeforeRenderObservable.removeCallback(func);
  25820. };
  25821. /**
  25822. * Registers a function to be called after every frame render
  25823. * @param func defines the function to register
  25824. */
  25825. Scene.prototype.registerAfterRender = function (func) {
  25826. this.onAfterRenderObservable.add(func);
  25827. };
  25828. /**
  25829. * Unregisters a function called after every frame render
  25830. * @param func defines the function to unregister
  25831. */
  25832. Scene.prototype.unregisterAfterRender = function (func) {
  25833. this.onAfterRenderObservable.removeCallback(func);
  25834. };
  25835. Scene.prototype._executeOnceBeforeRender = function (func) {
  25836. var _this = this;
  25837. var execFunc = function () {
  25838. func();
  25839. setTimeout(function () {
  25840. _this.unregisterBeforeRender(execFunc);
  25841. });
  25842. };
  25843. this.registerBeforeRender(execFunc);
  25844. };
  25845. /**
  25846. * The provided function will run before render once and will be disposed afterwards.
  25847. * A timeout delay can be provided so that the function will be executed in N ms.
  25848. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25849. * @param func The function to be executed.
  25850. * @param timeout optional delay in ms
  25851. */
  25852. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25853. var _this = this;
  25854. if (timeout !== undefined) {
  25855. setTimeout(function () {
  25856. _this._executeOnceBeforeRender(func);
  25857. }, timeout);
  25858. }
  25859. else {
  25860. this._executeOnceBeforeRender(func);
  25861. }
  25862. };
  25863. /** @hidden */
  25864. Scene.prototype._addPendingData = function (data) {
  25865. this._pendingData.push(data);
  25866. };
  25867. /** @hidden */
  25868. Scene.prototype._removePendingData = function (data) {
  25869. var wasLoading = this.isLoading;
  25870. var index = this._pendingData.indexOf(data);
  25871. if (index !== -1) {
  25872. this._pendingData.splice(index, 1);
  25873. }
  25874. if (wasLoading && !this.isLoading) {
  25875. this.onDataLoadedObservable.notifyObservers(this);
  25876. }
  25877. };
  25878. /**
  25879. * Returns the number of items waiting to be loaded
  25880. * @returns the number of items waiting to be loaded
  25881. */
  25882. Scene.prototype.getWaitingItemsCount = function () {
  25883. return this._pendingData.length;
  25884. };
  25885. Object.defineProperty(Scene.prototype, "isLoading", {
  25886. /**
  25887. * Returns a boolean indicating if the scene is still loading data
  25888. */
  25889. get: function () {
  25890. return this._pendingData.length > 0;
  25891. },
  25892. enumerable: true,
  25893. configurable: true
  25894. });
  25895. /**
  25896. * Registers a function to be executed when the scene is ready
  25897. * @param {Function} func - the function to be executed
  25898. */
  25899. Scene.prototype.executeWhenReady = function (func) {
  25900. var _this = this;
  25901. this.onReadyObservable.add(func);
  25902. if (this._executeWhenReadyTimeoutId !== -1) {
  25903. return;
  25904. }
  25905. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25906. _this._checkIsReady();
  25907. }, 150);
  25908. };
  25909. /**
  25910. * Returns a promise that resolves when the scene is ready
  25911. * @returns A promise that resolves when the scene is ready
  25912. */
  25913. Scene.prototype.whenReadyAsync = function () {
  25914. var _this = this;
  25915. return new Promise(function (resolve) {
  25916. _this.executeWhenReady(function () {
  25917. resolve();
  25918. });
  25919. });
  25920. };
  25921. /** @hidden */
  25922. Scene.prototype._checkIsReady = function () {
  25923. var _this = this;
  25924. if (this.isReady()) {
  25925. this.onReadyObservable.notifyObservers(this);
  25926. this.onReadyObservable.clear();
  25927. this._executeWhenReadyTimeoutId = -1;
  25928. return;
  25929. }
  25930. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25931. _this._checkIsReady();
  25932. }, 150);
  25933. };
  25934. // Animations
  25935. /**
  25936. * Will start the animation sequence of a given target
  25937. * @param target defines the target
  25938. * @param from defines from which frame should animation start
  25939. * @param to defines until which frame should animation run.
  25940. * @param weight defines the weight to apply to the animation (1.0 by default)
  25941. * @param loop defines if the animation loops
  25942. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25943. * @param onAnimationEnd defines the function to be executed when the animation ends
  25944. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25945. * @returns the animatable object created for this animation
  25946. */
  25947. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25948. if (weight === void 0) { weight = 1.0; }
  25949. if (speedRatio === void 0) { speedRatio = 1.0; }
  25950. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25951. returnedAnimatable.weight = weight;
  25952. return returnedAnimatable;
  25953. };
  25954. /**
  25955. * Will start the animation sequence of a given target
  25956. * @param target defines the target
  25957. * @param from defines from which frame should animation start
  25958. * @param to defines until which frame should animation run.
  25959. * @param loop defines if the animation loops
  25960. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25961. * @param onAnimationEnd defines the function to be executed when the animation ends
  25962. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25963. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25964. * @returns the animatable object created for this animation
  25965. */
  25966. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25967. if (speedRatio === void 0) { speedRatio = 1.0; }
  25968. if (stopCurrent === void 0) { stopCurrent = true; }
  25969. if (from > to && speedRatio > 0) {
  25970. speedRatio *= -1;
  25971. }
  25972. if (stopCurrent) {
  25973. this.stopAnimation(target);
  25974. }
  25975. if (!animatable) {
  25976. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25977. }
  25978. // Local animations
  25979. if (target.animations) {
  25980. animatable.appendAnimations(target, target.animations);
  25981. }
  25982. // Children animations
  25983. if (target.getAnimatables) {
  25984. var animatables = target.getAnimatables();
  25985. for (var index = 0; index < animatables.length; index++) {
  25986. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25987. }
  25988. }
  25989. animatable.reset();
  25990. return animatable;
  25991. };
  25992. /**
  25993. * Begin a new animation on a given node
  25994. * @param target defines the target where the animation will take place
  25995. * @param animations defines the list of animations to start
  25996. * @param from defines the initial value
  25997. * @param to defines the final value
  25998. * @param loop defines if you want animation to loop (off by default)
  25999. * @param speedRatio defines the speed ratio to apply to all animations
  26000. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26001. * @returns the list of created animatables
  26002. */
  26003. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26004. if (speedRatio === undefined) {
  26005. speedRatio = 1.0;
  26006. }
  26007. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26008. return animatable;
  26009. };
  26010. /**
  26011. * Begin a new animation on a given node and its hierarchy
  26012. * @param target defines the root node where the animation will take place
  26013. * @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.
  26014. * @param animations defines the list of animations to start
  26015. * @param from defines the initial value
  26016. * @param to defines the final value
  26017. * @param loop defines if you want animation to loop (off by default)
  26018. * @param speedRatio defines the speed ratio to apply to all animations
  26019. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26020. * @returns the list of animatables created for all nodes
  26021. */
  26022. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26023. var children = target.getDescendants(directDescendantsOnly);
  26024. var result = [];
  26025. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26026. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26027. var child = children_1[_i];
  26028. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26029. }
  26030. return result;
  26031. };
  26032. /**
  26033. * Gets the animatable associated with a specific target
  26034. * @param target defines the target of the animatable
  26035. * @returns the required animatable if found
  26036. */
  26037. Scene.prototype.getAnimatableByTarget = function (target) {
  26038. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26039. if (this._activeAnimatables[index].target === target) {
  26040. return this._activeAnimatables[index];
  26041. }
  26042. }
  26043. return null;
  26044. };
  26045. /**
  26046. * Gets all animatables associated with a given target
  26047. * @param target defines the target to look animatables for
  26048. * @returns an array of Animatables
  26049. */
  26050. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26051. var result = [];
  26052. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26053. if (this._activeAnimatables[index].target === target) {
  26054. result.push(this._activeAnimatables[index]);
  26055. }
  26056. }
  26057. return result;
  26058. };
  26059. Object.defineProperty(Scene.prototype, "animatables", {
  26060. /**
  26061. * Gets all animatable attached to the scene
  26062. */
  26063. get: function () {
  26064. return this._activeAnimatables;
  26065. },
  26066. enumerable: true,
  26067. configurable: true
  26068. });
  26069. /**
  26070. * Will stop the animation of the given target
  26071. * @param target - the target
  26072. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  26073. */
  26074. Scene.prototype.stopAnimation = function (target, animationName) {
  26075. var animatables = this.getAllAnimatablesByTarget(target);
  26076. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26077. var animatable = animatables_1[_i];
  26078. animatable.stop(animationName);
  26079. }
  26080. };
  26081. /**
  26082. * Stops and removes all animations that have been applied to the scene
  26083. */
  26084. Scene.prototype.stopAllAnimations = function () {
  26085. if (this._activeAnimatables) {
  26086. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26087. this._activeAnimatables[i].stop();
  26088. }
  26089. this._activeAnimatables = [];
  26090. }
  26091. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26092. var group = _a[_i];
  26093. group.stop();
  26094. }
  26095. };
  26096. Scene.prototype._animate = function () {
  26097. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26098. return;
  26099. }
  26100. // Getting time
  26101. var now = BABYLON.Tools.Now;
  26102. if (!this._animationTimeLast) {
  26103. if (this._pendingData.length > 0) {
  26104. return;
  26105. }
  26106. this._animationTimeLast = now;
  26107. }
  26108. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26109. this._animationTime += deltaTime;
  26110. this._animationTimeLast = now;
  26111. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26112. this._activeAnimatables[index]._animate(this._animationTime);
  26113. }
  26114. // Late animation bindings
  26115. this._processLateAnimationBindings();
  26116. };
  26117. /** @hidden */
  26118. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26119. var target = runtimeAnimation.target;
  26120. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26121. if (!target._lateAnimationHolders) {
  26122. target._lateAnimationHolders = {};
  26123. }
  26124. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26125. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26126. totalWeight: 0,
  26127. animations: [],
  26128. originalValue: originalValue
  26129. };
  26130. }
  26131. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26132. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26133. };
  26134. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26135. var normalizer = 1.0;
  26136. var finalPosition = BABYLON.Tmp.Vector3[0];
  26137. var finalScaling = BABYLON.Tmp.Vector3[1];
  26138. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26139. var startIndex = 0;
  26140. var originalAnimation = holder.animations[0];
  26141. var originalValue = holder.originalValue;
  26142. var scale = 1;
  26143. if (holder.totalWeight < 1.0) {
  26144. // We need to mix the original value in
  26145. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26146. scale = 1.0 - holder.totalWeight;
  26147. }
  26148. else {
  26149. startIndex = 1;
  26150. // We need to normalize the weights
  26151. normalizer = holder.totalWeight;
  26152. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26153. scale = originalAnimation.weight / normalizer;
  26154. if (scale == 1) {
  26155. return originalAnimation.currentValue;
  26156. }
  26157. }
  26158. finalScaling.scaleInPlace(scale);
  26159. finalPosition.scaleInPlace(scale);
  26160. finalQuaternion.scaleInPlace(scale);
  26161. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26162. var runtimeAnimation = holder.animations[animIndex];
  26163. var scale = runtimeAnimation.weight / normalizer;
  26164. var currentPosition = BABYLON.Tmp.Vector3[2];
  26165. var currentScaling = BABYLON.Tmp.Vector3[3];
  26166. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26167. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26168. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26169. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26170. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26171. }
  26172. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26173. return originalAnimation._workValue;
  26174. };
  26175. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26176. var originalAnimation = holder.animations[0];
  26177. var originalValue = holder.originalValue;
  26178. if (holder.animations.length === 1) {
  26179. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26180. }
  26181. var normalizer = 1.0;
  26182. var quaternions;
  26183. var weights;
  26184. if (holder.totalWeight < 1.0) {
  26185. var scale = 1.0 - holder.totalWeight;
  26186. quaternions = [];
  26187. weights = [];
  26188. quaternions.push(originalValue);
  26189. weights.push(scale);
  26190. }
  26191. else {
  26192. if (holder.animations.length === 2) { // Slerp as soon as we can
  26193. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26194. }
  26195. quaternions = [];
  26196. weights = [];
  26197. normalizer = holder.totalWeight;
  26198. }
  26199. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26200. var runtimeAnimation = holder.animations[animIndex];
  26201. quaternions.push(runtimeAnimation.currentValue);
  26202. weights.push(runtimeAnimation.weight / normalizer);
  26203. }
  26204. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26205. var cumulativeAmount = 0;
  26206. var cumulativeQuaternion = null;
  26207. for (var index = 0; index < quaternions.length;) {
  26208. if (!cumulativeQuaternion) {
  26209. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26210. cumulativeAmount = weights[index] + weights[index + 1];
  26211. index += 2;
  26212. continue;
  26213. }
  26214. cumulativeAmount += weights[index];
  26215. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26216. index++;
  26217. }
  26218. return cumulativeQuaternion;
  26219. };
  26220. Scene.prototype._processLateAnimationBindings = function () {
  26221. if (!this._registeredForLateAnimationBindings.length) {
  26222. return;
  26223. }
  26224. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26225. var target = this._registeredForLateAnimationBindings.data[index];
  26226. for (var path in target._lateAnimationHolders) {
  26227. var holder = target._lateAnimationHolders[path];
  26228. var originalAnimation = holder.animations[0];
  26229. var originalValue = holder.originalValue;
  26230. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26231. var finalValue = void 0;
  26232. if (matrixDecomposeMode) {
  26233. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26234. }
  26235. else {
  26236. var quaternionMode = originalValue.w !== undefined;
  26237. if (quaternionMode) {
  26238. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26239. }
  26240. else {
  26241. var startIndex = 0;
  26242. var normalizer = 1.0;
  26243. if (holder.totalWeight < 1.0) {
  26244. // We need to mix the original value in
  26245. if (originalValue.scale) {
  26246. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26247. }
  26248. else {
  26249. finalValue = originalValue * (1.0 - holder.totalWeight);
  26250. }
  26251. }
  26252. else {
  26253. // We need to normalize the weights
  26254. normalizer = holder.totalWeight;
  26255. var scale_1 = originalAnimation.weight / normalizer;
  26256. if (scale_1 !== 1) {
  26257. if (originalAnimation.currentValue.scale) {
  26258. finalValue = originalAnimation.currentValue.scale(scale_1);
  26259. }
  26260. else {
  26261. finalValue = originalAnimation.currentValue * scale_1;
  26262. }
  26263. }
  26264. else {
  26265. finalValue = originalAnimation.currentValue;
  26266. }
  26267. startIndex = 1;
  26268. }
  26269. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26270. var runtimeAnimation = holder.animations[animIndex];
  26271. var scale = runtimeAnimation.weight / normalizer;
  26272. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26273. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26274. }
  26275. else {
  26276. finalValue += runtimeAnimation.currentValue * scale;
  26277. }
  26278. }
  26279. }
  26280. }
  26281. target[path] = finalValue;
  26282. }
  26283. target._lateAnimationHolders = {};
  26284. }
  26285. this._registeredForLateAnimationBindings.reset();
  26286. };
  26287. // Matrix
  26288. /** @hidden */
  26289. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26290. this._useAlternateCameraConfiguration = active;
  26291. };
  26292. /**
  26293. * Gets the current view matrix
  26294. * @returns a Matrix
  26295. */
  26296. Scene.prototype.getViewMatrix = function () {
  26297. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26298. };
  26299. /**
  26300. * Gets the current projection matrix
  26301. * @returns a Matrix
  26302. */
  26303. Scene.prototype.getProjectionMatrix = function () {
  26304. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26305. };
  26306. /**
  26307. * Gets the current transform matrix
  26308. * @returns a Matrix made of View * Projection
  26309. */
  26310. Scene.prototype.getTransformMatrix = function () {
  26311. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26312. };
  26313. /**
  26314. * Sets the current transform matrix
  26315. * @param view defines the View matrix to use
  26316. * @param projection defines the Projection matrix to use
  26317. */
  26318. Scene.prototype.setTransformMatrix = function (view, projection) {
  26319. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26320. return;
  26321. }
  26322. this._viewUpdateFlag = view.updateFlag;
  26323. this._projectionUpdateFlag = projection.updateFlag;
  26324. this._viewMatrix = view;
  26325. this._projectionMatrix = projection;
  26326. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26327. // Update frustum
  26328. if (!this._frustumPlanes) {
  26329. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26330. }
  26331. else {
  26332. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26333. }
  26334. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26335. var otherCamera = this.activeCamera._alternateCamera;
  26336. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26337. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26338. }
  26339. if (this._sceneUbo.useUbo) {
  26340. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26341. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26342. this._sceneUbo.update();
  26343. }
  26344. };
  26345. /** @hidden */
  26346. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26347. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26348. return;
  26349. }
  26350. this._alternateViewUpdateFlag = view.updateFlag;
  26351. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26352. this._alternateViewMatrix = view;
  26353. this._alternateProjectionMatrix = projection;
  26354. if (!this._alternateTransformMatrix) {
  26355. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26356. }
  26357. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26358. if (!this._alternateSceneUbo) {
  26359. this._createAlternateUbo();
  26360. }
  26361. if (this._alternateSceneUbo.useUbo) {
  26362. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26363. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26364. this._alternateSceneUbo.update();
  26365. }
  26366. };
  26367. /**
  26368. * Gets the uniform buffer used to store scene data
  26369. * @returns a UniformBuffer
  26370. */
  26371. Scene.prototype.getSceneUniformBuffer = function () {
  26372. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26373. };
  26374. /**
  26375. * Gets an unique (relatively to the current scene) Id
  26376. * @returns an unique number for the scene
  26377. */
  26378. Scene.prototype.getUniqueId = function () {
  26379. var result = Scene._uniqueIdCounter;
  26380. Scene._uniqueIdCounter++;
  26381. return result;
  26382. };
  26383. /**
  26384. * Add a mesh to the list of scene's meshes
  26385. * @param newMesh defines the mesh to add
  26386. * @param recursive if all child meshes should also be added to the scene
  26387. */
  26388. Scene.prototype.addMesh = function (newMesh, recursive) {
  26389. var _this = this;
  26390. if (recursive === void 0) { recursive = false; }
  26391. this.meshes.push(newMesh);
  26392. //notify the collision coordinator
  26393. if (this.collisionCoordinator) {
  26394. this.collisionCoordinator.onMeshAdded(newMesh);
  26395. }
  26396. newMesh._resyncLightSources();
  26397. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26398. if (recursive) {
  26399. newMesh.getChildMeshes().forEach(function (m) {
  26400. _this.addMesh(m);
  26401. });
  26402. }
  26403. };
  26404. /**
  26405. * Remove a mesh for the list of scene's meshes
  26406. * @param toRemove defines the mesh to remove
  26407. * @param recursive if all child meshes should also be removed from the scene
  26408. * @returns the index where the mesh was in the mesh list
  26409. */
  26410. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26411. var _this = this;
  26412. if (recursive === void 0) { recursive = false; }
  26413. var index = this.meshes.indexOf(toRemove);
  26414. if (index !== -1) {
  26415. // Remove from the scene if mesh found
  26416. this.meshes.splice(index, 1);
  26417. }
  26418. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26419. if (recursive) {
  26420. toRemove.getChildMeshes().forEach(function (m) {
  26421. _this.removeMesh(m);
  26422. });
  26423. }
  26424. return index;
  26425. };
  26426. /**
  26427. * Add a transform node to the list of scene's transform nodes
  26428. * @param newTransformNode defines the transform node to add
  26429. */
  26430. Scene.prototype.addTransformNode = function (newTransformNode) {
  26431. this.transformNodes.push(newTransformNode);
  26432. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26433. };
  26434. /**
  26435. * Remove a transform node for the list of scene's transform nodes
  26436. * @param toRemove defines the transform node to remove
  26437. * @returns the index where the transform node was in the transform node list
  26438. */
  26439. Scene.prototype.removeTransformNode = function (toRemove) {
  26440. var index = this.transformNodes.indexOf(toRemove);
  26441. if (index !== -1) {
  26442. // Remove from the scene if found
  26443. this.transformNodes.splice(index, 1);
  26444. }
  26445. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26446. return index;
  26447. };
  26448. /**
  26449. * Remove a skeleton for the list of scene's skeletons
  26450. * @param toRemove defines the skeleton to remove
  26451. * @returns the index where the skeleton was in the skeleton list
  26452. */
  26453. Scene.prototype.removeSkeleton = function (toRemove) {
  26454. var index = this.skeletons.indexOf(toRemove);
  26455. if (index !== -1) {
  26456. // Remove from the scene if found
  26457. this.skeletons.splice(index, 1);
  26458. }
  26459. return index;
  26460. };
  26461. /**
  26462. * Remove a morph target for the list of scene's morph targets
  26463. * @param toRemove defines the morph target to remove
  26464. * @returns the index where the morph target was in the morph target list
  26465. */
  26466. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26467. var index = this.morphTargetManagers.indexOf(toRemove);
  26468. if (index !== -1) {
  26469. // Remove from the scene if found
  26470. this.morphTargetManagers.splice(index, 1);
  26471. }
  26472. return index;
  26473. };
  26474. /**
  26475. * Remove a light for the list of scene's lights
  26476. * @param toRemove defines the light to remove
  26477. * @returns the index where the light was in the light list
  26478. */
  26479. Scene.prototype.removeLight = function (toRemove) {
  26480. var index = this.lights.indexOf(toRemove);
  26481. if (index !== -1) {
  26482. // Remove from meshes
  26483. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26484. var mesh = _a[_i];
  26485. mesh._removeLightSource(toRemove);
  26486. }
  26487. // Remove from the scene if mesh found
  26488. this.lights.splice(index, 1);
  26489. this.sortLightsByPriority();
  26490. }
  26491. this.onLightRemovedObservable.notifyObservers(toRemove);
  26492. return index;
  26493. };
  26494. /**
  26495. * Remove a camera for the list of scene's cameras
  26496. * @param toRemove defines the camera to remove
  26497. * @returns the index where the camera was in the camera list
  26498. */
  26499. Scene.prototype.removeCamera = function (toRemove) {
  26500. var index = this.cameras.indexOf(toRemove);
  26501. if (index !== -1) {
  26502. // Remove from the scene if mesh found
  26503. this.cameras.splice(index, 1);
  26504. }
  26505. // Remove from activeCameras
  26506. var index2 = this.activeCameras.indexOf(toRemove);
  26507. if (index2 !== -1) {
  26508. // Remove from the scene if mesh found
  26509. this.activeCameras.splice(index2, 1);
  26510. }
  26511. // Reset the activeCamera
  26512. if (this.activeCamera === toRemove) {
  26513. if (this.cameras.length > 0) {
  26514. this.activeCamera = this.cameras[0];
  26515. }
  26516. else {
  26517. this.activeCamera = null;
  26518. }
  26519. }
  26520. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26521. return index;
  26522. };
  26523. /**
  26524. * Remove a particle system for the list of scene's particle systems
  26525. * @param toRemove defines the particle system to remove
  26526. * @returns the index where the particle system was in the particle system list
  26527. */
  26528. Scene.prototype.removeParticleSystem = function (toRemove) {
  26529. var index = this.particleSystems.indexOf(toRemove);
  26530. if (index !== -1) {
  26531. this.particleSystems.splice(index, 1);
  26532. }
  26533. return index;
  26534. };
  26535. /**
  26536. * Remove a animation for the list of scene's animations
  26537. * @param toRemove defines the animation to remove
  26538. * @returns the index where the animation was in the animation list
  26539. */
  26540. Scene.prototype.removeAnimation = function (toRemove) {
  26541. var index = this.animations.indexOf(toRemove);
  26542. if (index !== -1) {
  26543. this.animations.splice(index, 1);
  26544. }
  26545. return index;
  26546. };
  26547. /**
  26548. * Removes the given animation group from this scene.
  26549. * @param toRemove The animation group to remove
  26550. * @returns The index of the removed animation group
  26551. */
  26552. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26553. var index = this.animationGroups.indexOf(toRemove);
  26554. if (index !== -1) {
  26555. this.animationGroups.splice(index, 1);
  26556. }
  26557. return index;
  26558. };
  26559. /**
  26560. * Removes the given multi-material from this scene.
  26561. * @param toRemove The multi-material to remove
  26562. * @returns The index of the removed multi-material
  26563. */
  26564. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26565. var index = this.multiMaterials.indexOf(toRemove);
  26566. if (index !== -1) {
  26567. this.multiMaterials.splice(index, 1);
  26568. }
  26569. return index;
  26570. };
  26571. /**
  26572. * Removes the given material from this scene.
  26573. * @param toRemove The material to remove
  26574. * @returns The index of the removed material
  26575. */
  26576. Scene.prototype.removeMaterial = function (toRemove) {
  26577. var index = this.materials.indexOf(toRemove);
  26578. if (index !== -1) {
  26579. this.materials.splice(index, 1);
  26580. }
  26581. return index;
  26582. };
  26583. /**
  26584. * Removes the given lens flare system from this scene.
  26585. * @param toRemove The lens flare system to remove
  26586. * @returns The index of the removed lens flare system
  26587. */
  26588. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26589. var index = this.lensFlareSystems.indexOf(toRemove);
  26590. if (index !== -1) {
  26591. this.lensFlareSystems.splice(index, 1);
  26592. }
  26593. return index;
  26594. };
  26595. /**
  26596. * Removes the given action manager from this scene.
  26597. * @param toRemove The action manager to remove
  26598. * @returns The index of the removed action manager
  26599. */
  26600. Scene.prototype.removeActionManager = function (toRemove) {
  26601. var index = this._actionManagers.indexOf(toRemove);
  26602. if (index !== -1) {
  26603. this._actionManagers.splice(index, 1);
  26604. }
  26605. return index;
  26606. };
  26607. /**
  26608. * Removes the given effect layer from this scene.
  26609. * @param toRemove defines the effect layer to remove
  26610. * @returns the index of the removed effect layer
  26611. */
  26612. Scene.prototype.removeEffectLayer = function (toRemove) {
  26613. var index = this.effectLayers.indexOf(toRemove);
  26614. if (index !== -1) {
  26615. this.effectLayers.splice(index, 1);
  26616. }
  26617. return index;
  26618. };
  26619. /**
  26620. * Removes the given texture from this scene.
  26621. * @param toRemove The texture to remove
  26622. * @returns The index of the removed texture
  26623. */
  26624. Scene.prototype.removeTexture = function (toRemove) {
  26625. var index = this.textures.indexOf(toRemove);
  26626. if (index !== -1) {
  26627. this.textures.splice(index, 1);
  26628. }
  26629. return index;
  26630. };
  26631. /**
  26632. * Adds the given light to this scene
  26633. * @param newLight The light to add
  26634. */
  26635. Scene.prototype.addLight = function (newLight) {
  26636. this.lights.push(newLight);
  26637. this.sortLightsByPriority();
  26638. // Add light to all meshes (To support if the light is removed and then readded)
  26639. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26640. var mesh = _a[_i];
  26641. if (mesh._lightSources.indexOf(newLight) === -1) {
  26642. mesh._lightSources.push(newLight);
  26643. mesh._resyncLightSources();
  26644. }
  26645. }
  26646. this.onNewLightAddedObservable.notifyObservers(newLight);
  26647. };
  26648. /**
  26649. * Sorts the list list based on light priorities
  26650. */
  26651. Scene.prototype.sortLightsByPriority = function () {
  26652. if (this.requireLightSorting) {
  26653. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26654. }
  26655. };
  26656. /**
  26657. * Adds the given camera to this scene
  26658. * @param newCamera The camera to add
  26659. */
  26660. Scene.prototype.addCamera = function (newCamera) {
  26661. this.cameras.push(newCamera);
  26662. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26663. };
  26664. /**
  26665. * Adds the given skeleton to this scene
  26666. * @param newSkeleton The skeleton to add
  26667. */
  26668. Scene.prototype.addSkeleton = function (newSkeleton) {
  26669. this.skeletons.push(newSkeleton);
  26670. };
  26671. /**
  26672. * Adds the given particle system to this scene
  26673. * @param newParticleSystem The particle system to add
  26674. */
  26675. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26676. this.particleSystems.push(newParticleSystem);
  26677. };
  26678. /**
  26679. * Adds the given animation to this scene
  26680. * @param newAnimation The animation to add
  26681. */
  26682. Scene.prototype.addAnimation = function (newAnimation) {
  26683. this.animations.push(newAnimation);
  26684. };
  26685. /**
  26686. * Adds the given animation group to this scene.
  26687. * @param newAnimationGroup The animation group to add
  26688. */
  26689. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26690. this.animationGroups.push(newAnimationGroup);
  26691. };
  26692. /**
  26693. * Adds the given multi-material to this scene
  26694. * @param newMultiMaterial The multi-material to add
  26695. */
  26696. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26697. this.multiMaterials.push(newMultiMaterial);
  26698. };
  26699. /**
  26700. * Adds the given material to this scene
  26701. * @param newMaterial The material to add
  26702. */
  26703. Scene.prototype.addMaterial = function (newMaterial) {
  26704. this.materials.push(newMaterial);
  26705. };
  26706. /**
  26707. * Adds the given morph target to this scene
  26708. * @param newMorphTargetManager The morph target to add
  26709. */
  26710. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26711. this.morphTargetManagers.push(newMorphTargetManager);
  26712. };
  26713. /**
  26714. * Adds the given geometry to this scene
  26715. * @param newGeometry The geometry to add
  26716. */
  26717. Scene.prototype.addGeometry = function (newGeometry) {
  26718. this._geometries.push(newGeometry);
  26719. };
  26720. /**
  26721. * Adds the given lens flare system to this scene
  26722. * @param newLensFlareSystem The lens flare system to add
  26723. */
  26724. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26725. this.lensFlareSystems.push(newLensFlareSystem);
  26726. };
  26727. /**
  26728. * Adds the given effect layer to this scene
  26729. * @param newEffectLayer defines the effect layer to add
  26730. */
  26731. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26732. this.effectLayers.push(newEffectLayer);
  26733. };
  26734. /**
  26735. * Adds the given action manager to this scene
  26736. * @param newActionManager The action manager to add
  26737. */
  26738. Scene.prototype.addActionManager = function (newActionManager) {
  26739. this._actionManagers.push(newActionManager);
  26740. };
  26741. /**
  26742. * Adds the given texture to this scene.
  26743. * @param newTexture The texture to add
  26744. */
  26745. Scene.prototype.addTexture = function (newTexture) {
  26746. this.textures.push(newTexture);
  26747. };
  26748. /**
  26749. * Switch active camera
  26750. * @param newCamera defines the new active camera
  26751. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26752. */
  26753. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26754. if (attachControl === void 0) { attachControl = true; }
  26755. var canvas = this._engine.getRenderingCanvas();
  26756. if (!canvas) {
  26757. return;
  26758. }
  26759. if (this.activeCamera) {
  26760. this.activeCamera.detachControl(canvas);
  26761. }
  26762. this.activeCamera = newCamera;
  26763. if (attachControl) {
  26764. newCamera.attachControl(canvas);
  26765. }
  26766. };
  26767. /**
  26768. * sets the active camera of the scene using its ID
  26769. * @param id defines the camera's ID
  26770. * @return the new active camera or null if none found.
  26771. */
  26772. Scene.prototype.setActiveCameraByID = function (id) {
  26773. var camera = this.getCameraByID(id);
  26774. if (camera) {
  26775. this.activeCamera = camera;
  26776. return camera;
  26777. }
  26778. return null;
  26779. };
  26780. /**
  26781. * sets the active camera of the scene using its name
  26782. * @param name defines the camera's name
  26783. * @returns the new active camera or null if none found.
  26784. */
  26785. Scene.prototype.setActiveCameraByName = function (name) {
  26786. var camera = this.getCameraByName(name);
  26787. if (camera) {
  26788. this.activeCamera = camera;
  26789. return camera;
  26790. }
  26791. return null;
  26792. };
  26793. /**
  26794. * get an animation group using its name
  26795. * @param name defines the material's name
  26796. * @return the animation group or null if none found.
  26797. */
  26798. Scene.prototype.getAnimationGroupByName = function (name) {
  26799. for (var index = 0; index < this.animationGroups.length; index++) {
  26800. if (this.animationGroups[index].name === name) {
  26801. return this.animationGroups[index];
  26802. }
  26803. }
  26804. return null;
  26805. };
  26806. /**
  26807. * get a material using its id
  26808. * @param id defines the material's ID
  26809. * @return the material or null if none found.
  26810. */
  26811. Scene.prototype.getMaterialByID = function (id) {
  26812. for (var index = 0; index < this.materials.length; index++) {
  26813. if (this.materials[index].id === id) {
  26814. return this.materials[index];
  26815. }
  26816. }
  26817. return null;
  26818. };
  26819. /**
  26820. * Gets a material using its name
  26821. * @param name defines the material's name
  26822. * @return the material or null if none found.
  26823. */
  26824. Scene.prototype.getMaterialByName = function (name) {
  26825. for (var index = 0; index < this.materials.length; index++) {
  26826. if (this.materials[index].name === name) {
  26827. return this.materials[index];
  26828. }
  26829. }
  26830. return null;
  26831. };
  26832. /**
  26833. * Gets a lens flare system using its name
  26834. * @param name defines the name to look for
  26835. * @returns the lens flare system or null if not found
  26836. */
  26837. Scene.prototype.getLensFlareSystemByName = function (name) {
  26838. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26839. if (this.lensFlareSystems[index].name === name) {
  26840. return this.lensFlareSystems[index];
  26841. }
  26842. }
  26843. return null;
  26844. };
  26845. /**
  26846. * Gets a lens flare system using its id
  26847. * @param id defines the id to look for
  26848. * @returns the lens flare system or null if not found
  26849. */
  26850. Scene.prototype.getLensFlareSystemByID = function (id) {
  26851. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26852. if (this.lensFlareSystems[index].id === id) {
  26853. return this.lensFlareSystems[index];
  26854. }
  26855. }
  26856. return null;
  26857. };
  26858. /**
  26859. * Gets a camera using its id
  26860. * @param id defines the id to look for
  26861. * @returns the camera or null if not found
  26862. */
  26863. Scene.prototype.getCameraByID = function (id) {
  26864. for (var index = 0; index < this.cameras.length; index++) {
  26865. if (this.cameras[index].id === id) {
  26866. return this.cameras[index];
  26867. }
  26868. }
  26869. return null;
  26870. };
  26871. /**
  26872. * Gets a camera using its unique id
  26873. * @param uniqueId defines the unique id to look for
  26874. * @returns the camera or null if not found
  26875. */
  26876. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26877. for (var index = 0; index < this.cameras.length; index++) {
  26878. if (this.cameras[index].uniqueId === uniqueId) {
  26879. return this.cameras[index];
  26880. }
  26881. }
  26882. return null;
  26883. };
  26884. /**
  26885. * Gets a camera using its name
  26886. * @param name defines the camera's name
  26887. * @return the camera or null if none found.
  26888. */
  26889. Scene.prototype.getCameraByName = function (name) {
  26890. for (var index = 0; index < this.cameras.length; index++) {
  26891. if (this.cameras[index].name === name) {
  26892. return this.cameras[index];
  26893. }
  26894. }
  26895. return null;
  26896. };
  26897. /**
  26898. * Gets a bone using its id
  26899. * @param id defines the bone's id
  26900. * @return the bone or null if not found
  26901. */
  26902. Scene.prototype.getBoneByID = function (id) {
  26903. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26904. var skeleton = this.skeletons[skeletonIndex];
  26905. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26906. if (skeleton.bones[boneIndex].id === id) {
  26907. return skeleton.bones[boneIndex];
  26908. }
  26909. }
  26910. }
  26911. return null;
  26912. };
  26913. /**
  26914. * Gets a bone using its id
  26915. * @param name defines the bone's name
  26916. * @return the bone or null if not found
  26917. */
  26918. Scene.prototype.getBoneByName = function (name) {
  26919. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26920. var skeleton = this.skeletons[skeletonIndex];
  26921. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26922. if (skeleton.bones[boneIndex].name === name) {
  26923. return skeleton.bones[boneIndex];
  26924. }
  26925. }
  26926. }
  26927. return null;
  26928. };
  26929. /**
  26930. * Gets a light node using its name
  26931. * @param name defines the the light's name
  26932. * @return the light or null if none found.
  26933. */
  26934. Scene.prototype.getLightByName = function (name) {
  26935. for (var index = 0; index < this.lights.length; index++) {
  26936. if (this.lights[index].name === name) {
  26937. return this.lights[index];
  26938. }
  26939. }
  26940. return null;
  26941. };
  26942. /**
  26943. * Gets a light node using its id
  26944. * @param id defines the light's id
  26945. * @return the light or null if none found.
  26946. */
  26947. Scene.prototype.getLightByID = function (id) {
  26948. for (var index = 0; index < this.lights.length; index++) {
  26949. if (this.lights[index].id === id) {
  26950. return this.lights[index];
  26951. }
  26952. }
  26953. return null;
  26954. };
  26955. /**
  26956. * Gets a light node using its scene-generated unique ID
  26957. * @param uniqueId defines the light's unique id
  26958. * @return the light or null if none found.
  26959. */
  26960. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26961. for (var index = 0; index < this.lights.length; index++) {
  26962. if (this.lights[index].uniqueId === uniqueId) {
  26963. return this.lights[index];
  26964. }
  26965. }
  26966. return null;
  26967. };
  26968. /**
  26969. * Gets a particle system by id
  26970. * @param id defines the particle system id
  26971. * @return the corresponding system or null if none found
  26972. */
  26973. Scene.prototype.getParticleSystemByID = function (id) {
  26974. for (var index = 0; index < this.particleSystems.length; index++) {
  26975. if (this.particleSystems[index].id === id) {
  26976. return this.particleSystems[index];
  26977. }
  26978. }
  26979. return null;
  26980. };
  26981. /**
  26982. * Gets a geometry using its ID
  26983. * @param id defines the geometry's id
  26984. * @return the geometry or null if none found.
  26985. */
  26986. Scene.prototype.getGeometryByID = function (id) {
  26987. for (var index = 0; index < this._geometries.length; index++) {
  26988. if (this._geometries[index].id === id) {
  26989. return this._geometries[index];
  26990. }
  26991. }
  26992. return null;
  26993. };
  26994. /**
  26995. * Add a new geometry to this scene
  26996. * @param geometry defines the geometry to be added to the scene.
  26997. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26998. * @return a boolean defining if the geometry was added or not
  26999. */
  27000. Scene.prototype.pushGeometry = function (geometry, force) {
  27001. if (!force && this.getGeometryByID(geometry.id)) {
  27002. return false;
  27003. }
  27004. this._geometries.push(geometry);
  27005. //notify the collision coordinator
  27006. if (this.collisionCoordinator) {
  27007. this.collisionCoordinator.onGeometryAdded(geometry);
  27008. }
  27009. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27010. return true;
  27011. };
  27012. /**
  27013. * Removes an existing geometry
  27014. * @param geometry defines the geometry to be removed from the scene
  27015. * @return a boolean defining if the geometry was removed or not
  27016. */
  27017. Scene.prototype.removeGeometry = function (geometry) {
  27018. var index = this._geometries.indexOf(geometry);
  27019. if (index > -1) {
  27020. this._geometries.splice(index, 1);
  27021. //notify the collision coordinator
  27022. if (this.collisionCoordinator) {
  27023. this.collisionCoordinator.onGeometryDeleted(geometry);
  27024. }
  27025. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27026. return true;
  27027. }
  27028. return false;
  27029. };
  27030. /**
  27031. * Gets the list of geometries attached to the scene
  27032. * @returns an array of Geometry
  27033. */
  27034. Scene.prototype.getGeometries = function () {
  27035. return this._geometries;
  27036. };
  27037. /**
  27038. * Gets the first added mesh found of a given ID
  27039. * @param id defines the id to search for
  27040. * @return the mesh found or null if not found at all
  27041. */
  27042. Scene.prototype.getMeshByID = function (id) {
  27043. for (var index = 0; index < this.meshes.length; index++) {
  27044. if (this.meshes[index].id === id) {
  27045. return this.meshes[index];
  27046. }
  27047. }
  27048. return null;
  27049. };
  27050. /**
  27051. * Gets a list of meshes using their id
  27052. * @param id defines the id to search for
  27053. * @returns a list of meshes
  27054. */
  27055. Scene.prototype.getMeshesByID = function (id) {
  27056. return this.meshes.filter(function (m) {
  27057. return m.id === id;
  27058. });
  27059. };
  27060. /**
  27061. * Gets the first added transform node found of a given ID
  27062. * @param id defines the id to search for
  27063. * @return the found transform node or null if not found at all.
  27064. */
  27065. Scene.prototype.getTransformNodeByID = function (id) {
  27066. for (var index = 0; index < this.transformNodes.length; index++) {
  27067. if (this.transformNodes[index].id === id) {
  27068. return this.transformNodes[index];
  27069. }
  27070. }
  27071. return null;
  27072. };
  27073. /**
  27074. * Gets a list of transform nodes using their id
  27075. * @param id defines the id to search for
  27076. * @returns a list of transform nodes
  27077. */
  27078. Scene.prototype.getTransformNodesByID = function (id) {
  27079. return this.transformNodes.filter(function (m) {
  27080. return m.id === id;
  27081. });
  27082. };
  27083. /**
  27084. * Gets a mesh with its auto-generated unique id
  27085. * @param uniqueId defines the unique id to search for
  27086. * @return the found mesh or null if not found at all.
  27087. */
  27088. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27089. for (var index = 0; index < this.meshes.length; index++) {
  27090. if (this.meshes[index].uniqueId === uniqueId) {
  27091. return this.meshes[index];
  27092. }
  27093. }
  27094. return null;
  27095. };
  27096. /**
  27097. * Gets a the last added mesh using a given id
  27098. * @param id defines the id to search for
  27099. * @return the found mesh or null if not found at all.
  27100. */
  27101. Scene.prototype.getLastMeshByID = function (id) {
  27102. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27103. if (this.meshes[index].id === id) {
  27104. return this.meshes[index];
  27105. }
  27106. }
  27107. return null;
  27108. };
  27109. /**
  27110. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27111. * @param id defines the id to search for
  27112. * @return the found node or null if not found at all
  27113. */
  27114. Scene.prototype.getLastEntryByID = function (id) {
  27115. var index;
  27116. for (index = this.meshes.length - 1; index >= 0; index--) {
  27117. if (this.meshes[index].id === id) {
  27118. return this.meshes[index];
  27119. }
  27120. }
  27121. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27122. if (this.transformNodes[index].id === id) {
  27123. return this.transformNodes[index];
  27124. }
  27125. }
  27126. for (index = this.cameras.length - 1; index >= 0; index--) {
  27127. if (this.cameras[index].id === id) {
  27128. return this.cameras[index];
  27129. }
  27130. }
  27131. for (index = this.lights.length - 1; index >= 0; index--) {
  27132. if (this.lights[index].id === id) {
  27133. return this.lights[index];
  27134. }
  27135. }
  27136. return null;
  27137. };
  27138. /**
  27139. * Gets a node (Mesh, Camera, Light) using a given id
  27140. * @param id defines the id to search for
  27141. * @return the found node or null if not found at all
  27142. */
  27143. Scene.prototype.getNodeByID = function (id) {
  27144. var mesh = this.getMeshByID(id);
  27145. if (mesh) {
  27146. return mesh;
  27147. }
  27148. var light = this.getLightByID(id);
  27149. if (light) {
  27150. return light;
  27151. }
  27152. var camera = this.getCameraByID(id);
  27153. if (camera) {
  27154. return camera;
  27155. }
  27156. var bone = this.getBoneByID(id);
  27157. return bone;
  27158. };
  27159. /**
  27160. * Gets a node (Mesh, Camera, Light) using a given name
  27161. * @param name defines the name to search for
  27162. * @return the found node or null if not found at all.
  27163. */
  27164. Scene.prototype.getNodeByName = function (name) {
  27165. var mesh = this.getMeshByName(name);
  27166. if (mesh) {
  27167. return mesh;
  27168. }
  27169. var light = this.getLightByName(name);
  27170. if (light) {
  27171. return light;
  27172. }
  27173. var camera = this.getCameraByName(name);
  27174. if (camera) {
  27175. return camera;
  27176. }
  27177. var bone = this.getBoneByName(name);
  27178. return bone;
  27179. };
  27180. /**
  27181. * Gets a mesh using a given name
  27182. * @param name defines the name to search for
  27183. * @return the found mesh or null if not found at all.
  27184. */
  27185. Scene.prototype.getMeshByName = function (name) {
  27186. for (var index = 0; index < this.meshes.length; index++) {
  27187. if (this.meshes[index].name === name) {
  27188. return this.meshes[index];
  27189. }
  27190. }
  27191. return null;
  27192. };
  27193. /**
  27194. * Gets a transform node using a given name
  27195. * @param name defines the name to search for
  27196. * @return the found transform node or null if not found at all.
  27197. */
  27198. Scene.prototype.getTransformNodeByName = function (name) {
  27199. for (var index = 0; index < this.transformNodes.length; index++) {
  27200. if (this.transformNodes[index].name === name) {
  27201. return this.transformNodes[index];
  27202. }
  27203. }
  27204. return null;
  27205. };
  27206. /**
  27207. * Gets a sound using a given name
  27208. * @param name defines the name to search for
  27209. * @return the found sound or null if not found at all.
  27210. */
  27211. Scene.prototype.getSoundByName = function (name) {
  27212. var index;
  27213. if (BABYLON.AudioEngine) {
  27214. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27215. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27216. return this.mainSoundTrack.soundCollection[index];
  27217. }
  27218. }
  27219. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27220. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27221. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27222. return this.soundTracks[sdIndex].soundCollection[index];
  27223. }
  27224. }
  27225. }
  27226. }
  27227. return null;
  27228. };
  27229. /**
  27230. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27231. * @param id defines the id to search for
  27232. * @return the found skeleton or null if not found at all.
  27233. */
  27234. Scene.prototype.getLastSkeletonByID = function (id) {
  27235. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27236. if (this.skeletons[index].id === id) {
  27237. return this.skeletons[index];
  27238. }
  27239. }
  27240. return null;
  27241. };
  27242. /**
  27243. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27244. * @param id defines the id to search for
  27245. * @return the found skeleton or null if not found at all.
  27246. */
  27247. Scene.prototype.getSkeletonById = function (id) {
  27248. for (var index = 0; index < this.skeletons.length; index++) {
  27249. if (this.skeletons[index].id === id) {
  27250. return this.skeletons[index];
  27251. }
  27252. }
  27253. return null;
  27254. };
  27255. /**
  27256. * Gets a skeleton using a given name
  27257. * @param name defines the name to search for
  27258. * @return the found skeleton or null if not found at all.
  27259. */
  27260. Scene.prototype.getSkeletonByName = function (name) {
  27261. for (var index = 0; index < this.skeletons.length; index++) {
  27262. if (this.skeletons[index].name === name) {
  27263. return this.skeletons[index];
  27264. }
  27265. }
  27266. return null;
  27267. };
  27268. /**
  27269. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27270. * @param id defines the id to search for
  27271. * @return the found morph target manager or null if not found at all.
  27272. */
  27273. Scene.prototype.getMorphTargetManagerById = function (id) {
  27274. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27275. if (this.morphTargetManagers[index].uniqueId === id) {
  27276. return this.morphTargetManagers[index];
  27277. }
  27278. }
  27279. return null;
  27280. };
  27281. /**
  27282. * Gets a boolean indicating if the given mesh is active
  27283. * @param mesh defines the mesh to look for
  27284. * @returns true if the mesh is in the active list
  27285. */
  27286. Scene.prototype.isActiveMesh = function (mesh) {
  27287. return (this._activeMeshes.indexOf(mesh) !== -1);
  27288. };
  27289. /**
  27290. * Return a the first highlight layer of the scene with a given name.
  27291. * @param name The name of the highlight layer to look for.
  27292. * @return The highlight layer if found otherwise null.
  27293. */
  27294. Scene.prototype.getHighlightLayerByName = function (name) {
  27295. for (var index = 0; index < this.effectLayers.length; index++) {
  27296. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27297. return this.effectLayers[index];
  27298. }
  27299. }
  27300. return null;
  27301. };
  27302. /**
  27303. * Return a the first highlight layer of the scene with a given name.
  27304. * @param name The name of the highlight layer to look for.
  27305. * @return The highlight layer if found otherwise null.
  27306. */
  27307. Scene.prototype.getGlowLayerByName = function (name) {
  27308. for (var index = 0; index < this.effectLayers.length; index++) {
  27309. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27310. return this.effectLayers[index];
  27311. }
  27312. }
  27313. return null;
  27314. };
  27315. Object.defineProperty(Scene.prototype, "uid", {
  27316. /**
  27317. * Return a unique id as a string which can serve as an identifier for the scene
  27318. */
  27319. get: function () {
  27320. if (!this._uid) {
  27321. this._uid = BABYLON.Tools.RandomId();
  27322. }
  27323. return this._uid;
  27324. },
  27325. enumerable: true,
  27326. configurable: true
  27327. });
  27328. /**
  27329. * Add an externaly attached data from its key.
  27330. * This method call will fail and return false, if such key already exists.
  27331. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27332. * @param key the unique key that identifies the data
  27333. * @param data the data object to associate to the key for this Engine instance
  27334. * @return true if no such key were already present and the data was added successfully, false otherwise
  27335. */
  27336. Scene.prototype.addExternalData = function (key, data) {
  27337. if (!this._externalData) {
  27338. this._externalData = new BABYLON.StringDictionary();
  27339. }
  27340. return this._externalData.add(key, data);
  27341. };
  27342. /**
  27343. * Get an externaly attached data from its key
  27344. * @param key the unique key that identifies the data
  27345. * @return the associated data, if present (can be null), or undefined if not present
  27346. */
  27347. Scene.prototype.getExternalData = function (key) {
  27348. if (!this._externalData) {
  27349. return null;
  27350. }
  27351. return this._externalData.get(key);
  27352. };
  27353. /**
  27354. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27355. * @param key the unique key that identifies the data
  27356. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27357. * @return the associated data, can be null if the factory returned null.
  27358. */
  27359. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27360. if (!this._externalData) {
  27361. this._externalData = new BABYLON.StringDictionary();
  27362. }
  27363. return this._externalData.getOrAddWithFactory(key, factory);
  27364. };
  27365. /**
  27366. * Remove an externaly attached data from the Engine instance
  27367. * @param key the unique key that identifies the data
  27368. * @return true if the data was successfully removed, false if it doesn't exist
  27369. */
  27370. Scene.prototype.removeExternalData = function (key) {
  27371. return this._externalData.remove(key);
  27372. };
  27373. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27374. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27375. if (mesh.showSubMeshesBoundingBox) {
  27376. var boundingInfo = subMesh.getBoundingInfo();
  27377. if (boundingInfo !== null && boundingInfo !== undefined) {
  27378. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27379. }
  27380. }
  27381. var material = subMesh.getMaterial();
  27382. if (material !== null && material !== undefined) {
  27383. // Render targets
  27384. if (material.getRenderTargetTextures !== undefined) {
  27385. if (this._processedMaterials.indexOf(material) === -1) {
  27386. this._processedMaterials.push(material);
  27387. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27388. }
  27389. }
  27390. // Dispatch
  27391. this._activeIndices.addCount(subMesh.indexCount, false);
  27392. this._renderingManager.dispatch(subMesh, mesh, material);
  27393. }
  27394. }
  27395. };
  27396. /**
  27397. * Clear the processed materials smart array preventing retention point in material dispose.
  27398. */
  27399. Scene.prototype.freeProcessedMaterials = function () {
  27400. this._processedMaterials.dispose();
  27401. };
  27402. /**
  27403. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27404. */
  27405. Scene.prototype.freeActiveMeshes = function () {
  27406. this._activeMeshes.dispose();
  27407. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27408. this.activeCamera._activeMeshes.dispose();
  27409. }
  27410. if (this.activeCameras) {
  27411. for (var i = 0; i < this.activeCameras.length; i++) {
  27412. var activeCamera = this.activeCameras[i];
  27413. if (activeCamera && activeCamera._activeMeshes) {
  27414. activeCamera._activeMeshes.dispose();
  27415. }
  27416. }
  27417. }
  27418. };
  27419. /**
  27420. * Clear the info related to rendering groups preventing retention points during dispose.
  27421. */
  27422. Scene.prototype.freeRenderingGroups = function () {
  27423. if (this._renderingManager) {
  27424. this._renderingManager.freeRenderingGroups();
  27425. }
  27426. if (this.textures) {
  27427. for (var i = 0; i < this.textures.length; i++) {
  27428. var texture = this.textures[i];
  27429. if (texture && texture.renderList) {
  27430. texture.freeRenderingGroups();
  27431. }
  27432. }
  27433. }
  27434. };
  27435. /** @hidden */
  27436. Scene.prototype._isInIntermediateRendering = function () {
  27437. return this._intermediateRendering;
  27438. };
  27439. /**
  27440. * Defines the current active mesh candidate provider
  27441. * @param provider defines the provider to use
  27442. */
  27443. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27444. this._activeMeshCandidateProvider = provider;
  27445. };
  27446. /**
  27447. * Gets the current active mesh candidate provider
  27448. * @returns the current active mesh candidate provider
  27449. */
  27450. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27451. return this._activeMeshCandidateProvider;
  27452. };
  27453. /**
  27454. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27455. * @returns the current scene
  27456. */
  27457. Scene.prototype.freezeActiveMeshes = function () {
  27458. if (!this.activeCamera) {
  27459. return this;
  27460. }
  27461. if (!this._frustumPlanes) {
  27462. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27463. }
  27464. this._evaluateActiveMeshes();
  27465. this._activeMeshesFrozen = true;
  27466. return this;
  27467. };
  27468. /**
  27469. * Use this function to restart evaluating active meshes on every frame
  27470. * @returns the current scene
  27471. */
  27472. Scene.prototype.unfreezeActiveMeshes = function () {
  27473. this._activeMeshesFrozen = false;
  27474. return this;
  27475. };
  27476. Scene.prototype._evaluateActiveMeshes = function () {
  27477. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27478. return;
  27479. }
  27480. if (!this.activeCamera) {
  27481. return;
  27482. }
  27483. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27484. this.activeCamera._activeMeshes.reset();
  27485. this._activeMeshes.reset();
  27486. this._renderingManager.reset();
  27487. this._processedMaterials.reset();
  27488. this._activeParticleSystems.reset();
  27489. this._activeSkeletons.reset();
  27490. this._softwareSkinnedMeshes.reset();
  27491. if (this._boundingBoxRenderer) {
  27492. this._boundingBoxRenderer.reset();
  27493. }
  27494. // Meshes
  27495. var meshes;
  27496. var len;
  27497. var checkIsEnabled = true;
  27498. // Determine mesh candidates
  27499. if (this._activeMeshCandidateProvider !== undefined) {
  27500. // Use _activeMeshCandidateProvider
  27501. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27502. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27503. if (meshes !== undefined) {
  27504. len = meshes.length;
  27505. }
  27506. else {
  27507. len = 0;
  27508. }
  27509. }
  27510. else if (this._selectionOctree !== undefined) {
  27511. // Octree
  27512. var selection = this._selectionOctree.select(this._frustumPlanes);
  27513. meshes = selection.data;
  27514. len = selection.length;
  27515. }
  27516. else {
  27517. // Full scene traversal
  27518. len = this.meshes.length;
  27519. meshes = this.meshes;
  27520. }
  27521. // Check each mesh
  27522. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27523. mesh = meshes[meshIndex];
  27524. if (mesh.isBlocked) {
  27525. continue;
  27526. }
  27527. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27528. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27529. continue;
  27530. }
  27531. mesh.computeWorldMatrix();
  27532. // Intersections
  27533. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27534. this._meshesForIntersections.pushNoDuplicate(mesh);
  27535. }
  27536. // Switch to current LOD
  27537. meshLOD = mesh.getLOD(this.activeCamera);
  27538. if (meshLOD === undefined || meshLOD === null) {
  27539. continue;
  27540. }
  27541. mesh._preActivate();
  27542. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27543. this._activeMeshes.push(mesh);
  27544. this.activeCamera._activeMeshes.push(mesh);
  27545. mesh._activate(this._renderId);
  27546. if (meshLOD !== mesh) {
  27547. meshLOD._activate(this._renderId);
  27548. }
  27549. this._activeMesh(mesh, meshLOD);
  27550. }
  27551. }
  27552. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27553. // Particle systems
  27554. if (this.particlesEnabled) {
  27555. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27556. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27557. var particleSystem = this.particleSystems[particleIndex];
  27558. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27559. continue;
  27560. }
  27561. var emitter = particleSystem.emitter;
  27562. if (!emitter.position || emitter.isEnabled()) {
  27563. this._activeParticleSystems.push(particleSystem);
  27564. particleSystem.animate();
  27565. this._renderingManager.dispatchParticles(particleSystem);
  27566. }
  27567. }
  27568. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27569. }
  27570. };
  27571. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27572. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27573. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27574. mesh.skeleton.prepare();
  27575. }
  27576. if (!mesh.computeBonesUsingShaders) {
  27577. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27578. }
  27579. }
  27580. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27581. var boundingInfo = sourceMesh.getBoundingInfo();
  27582. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27583. }
  27584. if (mesh !== undefined && mesh !== null
  27585. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27586. // Submeshes Octrees
  27587. var len;
  27588. var subMeshes;
  27589. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27590. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27591. len = intersections.length;
  27592. subMeshes = intersections.data;
  27593. }
  27594. else {
  27595. subMeshes = mesh.subMeshes;
  27596. len = subMeshes.length;
  27597. }
  27598. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27599. subMesh = subMeshes[subIndex];
  27600. this._evaluateSubMesh(subMesh, mesh);
  27601. }
  27602. }
  27603. };
  27604. /**
  27605. * Update the transform matrix to update from the current active camera
  27606. * @param force defines a boolean used to force the update even if cache is up to date
  27607. */
  27608. Scene.prototype.updateTransformMatrix = function (force) {
  27609. if (!this.activeCamera) {
  27610. return;
  27611. }
  27612. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27613. };
  27614. /**
  27615. * 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)
  27616. * @param alternateCamera defines the camera to use
  27617. */
  27618. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27619. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27620. };
  27621. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27622. if (camera && camera._skipRendering) {
  27623. return;
  27624. }
  27625. var engine = this._engine;
  27626. this.activeCamera = camera;
  27627. if (!this.activeCamera)
  27628. throw new Error("Active camera not set");
  27629. // Viewport
  27630. engine.setViewport(this.activeCamera.viewport);
  27631. // Camera
  27632. this.resetCachedMaterial();
  27633. this._renderId++;
  27634. this.updateTransformMatrix();
  27635. if (camera._alternateCamera) {
  27636. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27637. this._alternateRendering = true;
  27638. }
  27639. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27640. // Meshes
  27641. this._evaluateActiveMeshes();
  27642. // Software skinning
  27643. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27644. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27645. mesh.applySkeleton(mesh.skeleton);
  27646. }
  27647. // Render targets
  27648. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27649. var needsRestoreFrameBuffer = false;
  27650. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27651. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27652. }
  27653. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27654. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27655. }
  27656. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27657. this._intermediateRendering = true;
  27658. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27659. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27660. var renderTarget = this._renderTargets.data[renderIndex];
  27661. if (renderTarget._shouldRender()) {
  27662. this._renderId++;
  27663. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27664. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27665. }
  27666. }
  27667. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27668. this._intermediateRendering = false;
  27669. this._renderId++;
  27670. needsRestoreFrameBuffer = true; // Restore back buffer
  27671. }
  27672. // Render EffectLayer Texture
  27673. var stencilState = this._engine.getStencilBuffer();
  27674. var renderEffects = false;
  27675. var needStencil = false;
  27676. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27677. this._intermediateRendering = true;
  27678. for (var i = 0; i < this.effectLayers.length; i++) {
  27679. var effectLayer = this.effectLayers[i];
  27680. if (effectLayer.shouldRender() &&
  27681. (!effectLayer.camera ||
  27682. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27683. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27684. renderEffects = true;
  27685. needStencil = needStencil || effectLayer.needStencil();
  27686. var renderTarget = effectLayer._mainTexture;
  27687. if (renderTarget._shouldRender()) {
  27688. this._renderId++;
  27689. renderTarget.render(false, false);
  27690. needsRestoreFrameBuffer = true;
  27691. }
  27692. }
  27693. }
  27694. this._intermediateRendering = false;
  27695. this._renderId++;
  27696. }
  27697. if (needsRestoreFrameBuffer) {
  27698. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27699. }
  27700. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27701. // Prepare Frame
  27702. if (this.postProcessManager) {
  27703. this.postProcessManager._prepareFrame();
  27704. }
  27705. // Backgrounds
  27706. var layerIndex;
  27707. var layer;
  27708. if (this.layers.length) {
  27709. engine.setDepthBuffer(false);
  27710. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27711. layer = this.layers[layerIndex];
  27712. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27713. layer.render();
  27714. }
  27715. }
  27716. engine.setDepthBuffer(true);
  27717. }
  27718. // Activate effect Layer stencil
  27719. if (needStencil) {
  27720. this._engine.setStencilBuffer(true);
  27721. }
  27722. // Render
  27723. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27724. this._renderingManager.render(null, null, true, true);
  27725. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27726. // Restore effect Layer stencil
  27727. if (needStencil) {
  27728. this._engine.setStencilBuffer(stencilState);
  27729. }
  27730. // Bounding boxes
  27731. if (this._boundingBoxRenderer) {
  27732. this._boundingBoxRenderer.render();
  27733. }
  27734. // Lens flares
  27735. if (this.lensFlaresEnabled) {
  27736. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27737. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27738. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27739. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27740. lensFlareSystem.render();
  27741. }
  27742. }
  27743. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27744. }
  27745. // Effect Layer
  27746. if (renderEffects) {
  27747. engine.setDepthBuffer(false);
  27748. for (var i = 0; i < this.effectLayers.length; i++) {
  27749. if (this.effectLayers[i].shouldRender()) {
  27750. this.effectLayers[i].render();
  27751. }
  27752. }
  27753. engine.setDepthBuffer(true);
  27754. }
  27755. // Foregrounds
  27756. if (this.layers.length) {
  27757. engine.setDepthBuffer(false);
  27758. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27759. layer = this.layers[layerIndex];
  27760. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27761. layer.render();
  27762. }
  27763. }
  27764. engine.setDepthBuffer(true);
  27765. }
  27766. // Finalize frame
  27767. if (this.postProcessManager) {
  27768. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27769. }
  27770. // Reset some special arrays
  27771. this._renderTargets.reset();
  27772. this._alternateRendering = false;
  27773. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27774. };
  27775. Scene.prototype._processSubCameras = function (camera) {
  27776. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27777. this._renderForCamera(camera);
  27778. return;
  27779. }
  27780. // rig cameras
  27781. for (var index = 0; index < camera._rigCameras.length; index++) {
  27782. this._renderForCamera(camera._rigCameras[index], camera);
  27783. }
  27784. this.activeCamera = camera;
  27785. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27786. };
  27787. Scene.prototype._checkIntersections = function () {
  27788. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27789. var sourceMesh = this._meshesForIntersections.data[index];
  27790. if (!sourceMesh.actionManager) {
  27791. continue;
  27792. }
  27793. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27794. var action = sourceMesh.actionManager.actions[actionIndex];
  27795. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27796. var parameters = action.getTriggerParameter();
  27797. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27798. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27799. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27800. if (areIntersecting && currentIntersectionInProgress === -1) {
  27801. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27802. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27803. sourceMesh._intersectionsInProgress.push(otherMesh);
  27804. }
  27805. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27806. sourceMesh._intersectionsInProgress.push(otherMesh);
  27807. }
  27808. }
  27809. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27810. //They intersected, and now they don't.
  27811. //is this trigger an exit trigger? execute an event.
  27812. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27813. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27814. }
  27815. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27816. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27817. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27818. return otherMesh === parameterMesh;
  27819. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27820. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27821. }
  27822. }
  27823. }
  27824. }
  27825. }
  27826. };
  27827. /**
  27828. * Render the scene
  27829. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27830. */
  27831. Scene.prototype.render = function (updateCameras) {
  27832. if (updateCameras === void 0) { updateCameras = true; }
  27833. if (this.isDisposed) {
  27834. return;
  27835. }
  27836. this._activeParticles.fetchNewFrame();
  27837. this._totalVertices.fetchNewFrame();
  27838. this._activeIndices.fetchNewFrame();
  27839. this._activeBones.fetchNewFrame();
  27840. this._meshesForIntersections.reset();
  27841. this.resetCachedMaterial();
  27842. this.onBeforeAnimationsObservable.notifyObservers(this);
  27843. // Actions
  27844. if (this.actionManager) {
  27845. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27846. }
  27847. //Simplification Queue
  27848. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27849. this.simplificationQueue.executeNext();
  27850. }
  27851. if (this._engine.isDeterministicLockStep()) {
  27852. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27853. var defaultFPS = (60.0 / 1000.0);
  27854. var defaultFrameTime = 1000 / 60; // frame time in MS
  27855. if (this._physicsEngine) {
  27856. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27857. }
  27858. var stepsTaken = 0;
  27859. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27860. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27861. internalSteps = Math.min(internalSteps, maxSubSteps);
  27862. do {
  27863. this.onBeforeStepObservable.notifyObservers(this);
  27864. // Animations
  27865. this._animationRatio = defaultFrameTime * defaultFPS;
  27866. this._animate();
  27867. this.onAfterAnimationsObservable.notifyObservers(this);
  27868. // Physics
  27869. if (this._physicsEngine) {
  27870. this.onBeforePhysicsObservable.notifyObservers(this);
  27871. this._physicsEngine._step(defaultFrameTime / 1000);
  27872. this.onAfterPhysicsObservable.notifyObservers(this);
  27873. }
  27874. this.onAfterStepObservable.notifyObservers(this);
  27875. this._currentStepId++;
  27876. stepsTaken++;
  27877. deltaTime -= defaultFrameTime;
  27878. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27879. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27880. }
  27881. else {
  27882. // Animations
  27883. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27884. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27885. this._animate();
  27886. this.onAfterAnimationsObservable.notifyObservers(this);
  27887. // Physics
  27888. if (this._physicsEngine) {
  27889. this.onBeforePhysicsObservable.notifyObservers(this);
  27890. this._physicsEngine._step(deltaTime / 1000.0);
  27891. this.onAfterPhysicsObservable.notifyObservers(this);
  27892. }
  27893. }
  27894. // update gamepad manager
  27895. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27896. this._gamepadManager._checkGamepadsStatus();
  27897. }
  27898. // Update Cameras
  27899. if (updateCameras) {
  27900. if (this.activeCameras.length > 0) {
  27901. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27902. var camera = this.activeCameras[cameraIndex];
  27903. camera.update();
  27904. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27905. // rig cameras
  27906. for (var index = 0; index < camera._rigCameras.length; index++) {
  27907. camera._rigCameras[index].update();
  27908. }
  27909. }
  27910. }
  27911. }
  27912. else if (this.activeCamera) {
  27913. this.activeCamera.update();
  27914. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27915. // rig cameras
  27916. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27917. this.activeCamera._rigCameras[index].update();
  27918. }
  27919. }
  27920. }
  27921. }
  27922. // Before render
  27923. this.onBeforeRenderObservable.notifyObservers(this);
  27924. // Customs render targets
  27925. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27926. var engine = this.getEngine();
  27927. var currentActiveCamera = this.activeCamera;
  27928. if (this.renderTargetsEnabled) {
  27929. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27930. this._intermediateRendering = true;
  27931. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27932. var renderTarget = this.customRenderTargets[customIndex];
  27933. if (renderTarget._shouldRender()) {
  27934. this._renderId++;
  27935. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27936. if (!this.activeCamera)
  27937. throw new Error("Active camera not set");
  27938. // Viewport
  27939. engine.setViewport(this.activeCamera.viewport);
  27940. // Camera
  27941. this.updateTransformMatrix();
  27942. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27943. }
  27944. }
  27945. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27946. this._intermediateRendering = false;
  27947. this._renderId++;
  27948. }
  27949. // Restore back buffer
  27950. if (this.customRenderTargets.length > 0) {
  27951. engine.restoreDefaultFramebuffer();
  27952. }
  27953. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27954. this.activeCamera = currentActiveCamera;
  27955. // Procedural textures
  27956. if (this.proceduralTexturesEnabled) {
  27957. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27958. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27959. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27960. if (proceduralTexture._shouldRender()) {
  27961. proceduralTexture.render();
  27962. }
  27963. }
  27964. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27965. }
  27966. // Clear
  27967. if (this.autoClearDepthAndStencil || this.autoClear) {
  27968. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27969. }
  27970. // Shadows
  27971. if (this.shadowsEnabled) {
  27972. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27973. var light = this.lights[lightIndex];
  27974. var shadowGenerator = light.getShadowGenerator();
  27975. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27976. var shadowMap = (shadowGenerator.getShadowMap());
  27977. if (this.textures.indexOf(shadowMap) !== -1) {
  27978. this._renderTargets.push(shadowMap);
  27979. }
  27980. }
  27981. }
  27982. }
  27983. // Depth renderer
  27984. for (var key in this._depthRenderer) {
  27985. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27986. }
  27987. // Geometry renderer
  27988. if (this._geometryBufferRenderer) {
  27989. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27990. }
  27991. // RenderPipeline
  27992. if (this._postProcessRenderPipelineManager) {
  27993. this._postProcessRenderPipelineManager.update();
  27994. }
  27995. // Multi-cameras?
  27996. if (this.activeCameras.length > 0) {
  27997. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27998. if (cameraIndex > 0) {
  27999. this._engine.clear(null, false, true, true);
  28000. }
  28001. this._processSubCameras(this.activeCameras[cameraIndex]);
  28002. }
  28003. }
  28004. else {
  28005. if (!this.activeCamera) {
  28006. throw new Error("No camera defined");
  28007. }
  28008. this._processSubCameras(this.activeCamera);
  28009. }
  28010. // Intersection checks
  28011. this._checkIntersections();
  28012. // Update the audio listener attached to the camera
  28013. if (BABYLON.AudioEngine) {
  28014. this._updateAudioParameters();
  28015. }
  28016. // After render
  28017. if (this.afterRender) {
  28018. this.afterRender();
  28019. }
  28020. this.onAfterRenderObservable.notifyObservers(this);
  28021. // Cleaning
  28022. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28023. var data = this._toBeDisposed.data[index];
  28024. if (data) {
  28025. data.dispose();
  28026. }
  28027. this._toBeDisposed[index] = null;
  28028. }
  28029. this._toBeDisposed.reset();
  28030. if (this.dumpNextRenderTargets) {
  28031. this.dumpNextRenderTargets = false;
  28032. }
  28033. this._activeBones.addCount(0, true);
  28034. this._activeIndices.addCount(0, true);
  28035. this._activeParticles.addCount(0, true);
  28036. };
  28037. Scene.prototype._updateAudioParameters = function () {
  28038. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  28039. return;
  28040. }
  28041. var listeningCamera;
  28042. var audioEngine = BABYLON.Engine.audioEngine;
  28043. if (this.activeCameras.length > 0) {
  28044. listeningCamera = this.activeCameras[0];
  28045. }
  28046. else {
  28047. listeningCamera = this.activeCamera;
  28048. }
  28049. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  28050. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  28051. // for VR cameras
  28052. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  28053. listeningCamera = listeningCamera.rigCameras[0];
  28054. }
  28055. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  28056. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  28057. cameraDirection.normalize();
  28058. // To avoid some errors on GearVR
  28059. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  28060. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  28061. }
  28062. var i;
  28063. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28064. var sound = this.mainSoundTrack.soundCollection[i];
  28065. if (sound.useCustomAttenuation) {
  28066. sound.updateDistanceFromListener();
  28067. }
  28068. }
  28069. for (i = 0; i < this.soundTracks.length; i++) {
  28070. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28071. sound = this.soundTracks[i].soundCollection[j];
  28072. if (sound.useCustomAttenuation) {
  28073. sound.updateDistanceFromListener();
  28074. }
  28075. }
  28076. }
  28077. }
  28078. };
  28079. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28080. // Audio
  28081. /**
  28082. * Gets or sets if audio support is enabled
  28083. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28084. */
  28085. get: function () {
  28086. return this._audioEnabled;
  28087. },
  28088. set: function (value) {
  28089. this._audioEnabled = value;
  28090. if (BABYLON.AudioEngine) {
  28091. if (this._audioEnabled) {
  28092. this._enableAudio();
  28093. }
  28094. else {
  28095. this._disableAudio();
  28096. }
  28097. }
  28098. },
  28099. enumerable: true,
  28100. configurable: true
  28101. });
  28102. Scene.prototype._disableAudio = function () {
  28103. var i;
  28104. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28105. this.mainSoundTrack.soundCollection[i].pause();
  28106. }
  28107. for (i = 0; i < this.soundTracks.length; i++) {
  28108. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28109. this.soundTracks[i].soundCollection[j].pause();
  28110. }
  28111. }
  28112. };
  28113. Scene.prototype._enableAudio = function () {
  28114. var i;
  28115. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28116. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28117. this.mainSoundTrack.soundCollection[i].play();
  28118. }
  28119. }
  28120. for (i = 0; i < this.soundTracks.length; i++) {
  28121. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28122. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28123. this.soundTracks[i].soundCollection[j].play();
  28124. }
  28125. }
  28126. }
  28127. };
  28128. Object.defineProperty(Scene.prototype, "headphone", {
  28129. /**
  28130. * Gets or sets if audio will be output to headphones
  28131. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28132. */
  28133. get: function () {
  28134. return this._headphone;
  28135. },
  28136. set: function (value) {
  28137. this._headphone = value;
  28138. if (BABYLON.AudioEngine) {
  28139. if (this._headphone) {
  28140. this._switchAudioModeForHeadphones();
  28141. }
  28142. else {
  28143. this._switchAudioModeForNormalSpeakers();
  28144. }
  28145. }
  28146. },
  28147. enumerable: true,
  28148. configurable: true
  28149. });
  28150. Scene.prototype._switchAudioModeForHeadphones = function () {
  28151. this.mainSoundTrack.switchPanningModelToHRTF();
  28152. for (var i = 0; i < this.soundTracks.length; i++) {
  28153. this.soundTracks[i].switchPanningModelToHRTF();
  28154. }
  28155. };
  28156. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28157. this.mainSoundTrack.switchPanningModelToEqualPower();
  28158. for (var i = 0; i < this.soundTracks.length; i++) {
  28159. this.soundTracks[i].switchPanningModelToEqualPower();
  28160. }
  28161. };
  28162. /**
  28163. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28164. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28165. * @returns the created depth renderer
  28166. */
  28167. Scene.prototype.enableDepthRenderer = function (camera) {
  28168. camera = camera || this.activeCamera;
  28169. if (!camera) {
  28170. throw "No camera available to enable depth renderer";
  28171. }
  28172. if (!this._depthRenderer[camera.id]) {
  28173. var textureType = 0;
  28174. if (this._engine.getCaps().textureHalfFloatRender) {
  28175. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28176. }
  28177. else if (this._engine.getCaps().textureFloatRender) {
  28178. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28179. }
  28180. else {
  28181. throw "Depth renderer does not support int texture type";
  28182. }
  28183. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28184. }
  28185. return this._depthRenderer[camera.id];
  28186. };
  28187. /**
  28188. * Disables a depth renderer for a given camera
  28189. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28190. */
  28191. Scene.prototype.disableDepthRenderer = function (camera) {
  28192. camera = camera || this.activeCamera;
  28193. if (!camera || !this._depthRenderer[camera.id]) {
  28194. return;
  28195. }
  28196. this._depthRenderer[camera.id].dispose();
  28197. delete this._depthRenderer[camera.id];
  28198. };
  28199. /**
  28200. * Enables a GeometryBufferRender and associates it with the scene
  28201. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28202. * @returns the GeometryBufferRenderer
  28203. */
  28204. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28205. if (ratio === void 0) { ratio = 1; }
  28206. if (this._geometryBufferRenderer) {
  28207. return this._geometryBufferRenderer;
  28208. }
  28209. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28210. if (!this._geometryBufferRenderer.isSupported) {
  28211. this._geometryBufferRenderer = null;
  28212. }
  28213. return this._geometryBufferRenderer;
  28214. };
  28215. /**
  28216. * Disables the GeometryBufferRender associated with the scene
  28217. */
  28218. Scene.prototype.disableGeometryBufferRenderer = function () {
  28219. if (!this._geometryBufferRenderer) {
  28220. return;
  28221. }
  28222. this._geometryBufferRenderer.dispose();
  28223. this._geometryBufferRenderer = null;
  28224. };
  28225. /**
  28226. * Freeze all materials
  28227. * A frozen material will not be updatable but should be faster to render
  28228. */
  28229. Scene.prototype.freezeMaterials = function () {
  28230. for (var i = 0; i < this.materials.length; i++) {
  28231. this.materials[i].freeze();
  28232. }
  28233. };
  28234. /**
  28235. * Unfreeze all materials
  28236. * A frozen material will not be updatable but should be faster to render
  28237. */
  28238. Scene.prototype.unfreezeMaterials = function () {
  28239. for (var i = 0; i < this.materials.length; i++) {
  28240. this.materials[i].unfreeze();
  28241. }
  28242. };
  28243. /**
  28244. * Releases all held ressources
  28245. */
  28246. Scene.prototype.dispose = function () {
  28247. this.beforeRender = null;
  28248. this.afterRender = null;
  28249. this.skeletons = [];
  28250. this.morphTargetManagers = [];
  28251. this.importedMeshesFiles = new Array();
  28252. this.stopAllAnimations();
  28253. this.resetCachedMaterial();
  28254. for (var key in this._depthRenderer) {
  28255. this._depthRenderer[key].dispose();
  28256. }
  28257. if (this._gamepadManager) {
  28258. this._gamepadManager.dispose();
  28259. this._gamepadManager = null;
  28260. }
  28261. // Smart arrays
  28262. if (this.activeCamera) {
  28263. this.activeCamera._activeMeshes.dispose();
  28264. this.activeCamera = null;
  28265. }
  28266. this._activeMeshes.dispose();
  28267. this._renderingManager.dispose();
  28268. this._processedMaterials.dispose();
  28269. this._activeParticleSystems.dispose();
  28270. this._activeSkeletons.dispose();
  28271. this._softwareSkinnedMeshes.dispose();
  28272. this._renderTargets.dispose();
  28273. this._registeredForLateAnimationBindings.dispose();
  28274. if (this._boundingBoxRenderer) {
  28275. this._boundingBoxRenderer.dispose();
  28276. }
  28277. this._meshesForIntersections.dispose();
  28278. this._toBeDisposed.dispose();
  28279. // Abort active requests
  28280. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28281. var request = _a[_i];
  28282. request.abort();
  28283. }
  28284. // Debug layer
  28285. if (this._debugLayer) {
  28286. this._debugLayer.hide();
  28287. }
  28288. // Events
  28289. this.onDisposeObservable.notifyObservers(this);
  28290. this.onDisposeObservable.clear();
  28291. this.onBeforeRenderObservable.clear();
  28292. this.onAfterRenderObservable.clear();
  28293. this.onBeforeRenderTargetsRenderObservable.clear();
  28294. this.onAfterRenderTargetsRenderObservable.clear();
  28295. this.onAfterStepObservable.clear();
  28296. this.onBeforeStepObservable.clear();
  28297. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28298. this.onAfterActiveMeshesEvaluationObservable.clear();
  28299. this.onBeforeParticlesRenderingObservable.clear();
  28300. this.onAfterParticlesRenderingObservable.clear();
  28301. this.onBeforeSpritesRenderingObservable.clear();
  28302. this.onAfterSpritesRenderingObservable.clear();
  28303. this.onBeforeDrawPhaseObservable.clear();
  28304. this.onAfterDrawPhaseObservable.clear();
  28305. this.onBeforePhysicsObservable.clear();
  28306. this.onAfterPhysicsObservable.clear();
  28307. this.onBeforeAnimationsObservable.clear();
  28308. this.onAfterAnimationsObservable.clear();
  28309. this.onDataLoadedObservable.clear();
  28310. this.detachControl();
  28311. // Release sounds & sounds tracks
  28312. if (BABYLON.AudioEngine) {
  28313. this.disposeSounds();
  28314. }
  28315. // VR Helper
  28316. if (this.VRHelper) {
  28317. this.VRHelper.dispose();
  28318. }
  28319. // Detach cameras
  28320. var canvas = this._engine.getRenderingCanvas();
  28321. if (canvas) {
  28322. var index;
  28323. for (index = 0; index < this.cameras.length; index++) {
  28324. this.cameras[index].detachControl(canvas);
  28325. }
  28326. }
  28327. // Release animation groups
  28328. while (this.animationGroups.length) {
  28329. this.animationGroups[0].dispose();
  28330. }
  28331. // Release lights
  28332. while (this.lights.length) {
  28333. this.lights[0].dispose();
  28334. }
  28335. // Release meshes
  28336. while (this.meshes.length) {
  28337. this.meshes[0].dispose(true);
  28338. }
  28339. while (this.transformNodes.length) {
  28340. this.removeTransformNode(this.transformNodes[0]);
  28341. }
  28342. // Release cameras
  28343. while (this.cameras.length) {
  28344. this.cameras[0].dispose();
  28345. }
  28346. // Release materials
  28347. if (this.defaultMaterial) {
  28348. this.defaultMaterial.dispose();
  28349. }
  28350. while (this.multiMaterials.length) {
  28351. this.multiMaterials[0].dispose();
  28352. }
  28353. while (this.materials.length) {
  28354. this.materials[0].dispose();
  28355. }
  28356. // Release particles
  28357. while (this.particleSystems.length) {
  28358. this.particleSystems[0].dispose();
  28359. }
  28360. // Release sprites
  28361. while (this.spriteManagers.length) {
  28362. this.spriteManagers[0].dispose();
  28363. }
  28364. // Release postProcesses
  28365. while (this.postProcesses.length) {
  28366. this.postProcesses[0].dispose();
  28367. }
  28368. // Release layers
  28369. while (this.layers.length) {
  28370. this.layers[0].dispose();
  28371. }
  28372. while (this.effectLayers.length) {
  28373. this.effectLayers[0].dispose();
  28374. }
  28375. // Release textures
  28376. while (this.textures.length) {
  28377. this.textures[0].dispose();
  28378. }
  28379. // Release UBO
  28380. this._sceneUbo.dispose();
  28381. if (this._alternateSceneUbo) {
  28382. this._alternateSceneUbo.dispose();
  28383. }
  28384. // Post-processes
  28385. this.postProcessManager.dispose();
  28386. if (this._postProcessRenderPipelineManager) {
  28387. this._postProcessRenderPipelineManager.dispose();
  28388. }
  28389. // Physics
  28390. if (this._physicsEngine) {
  28391. this.disablePhysicsEngine();
  28392. }
  28393. // Remove from engine
  28394. index = this._engine.scenes.indexOf(this);
  28395. if (index > -1) {
  28396. this._engine.scenes.splice(index, 1);
  28397. }
  28398. this._engine.wipeCaches(true);
  28399. this._isDisposed = true;
  28400. };
  28401. Object.defineProperty(Scene.prototype, "isDisposed", {
  28402. /**
  28403. * Gets if the scene is already disposed
  28404. */
  28405. get: function () {
  28406. return this._isDisposed;
  28407. },
  28408. enumerable: true,
  28409. configurable: true
  28410. });
  28411. /**
  28412. * Releases sounds & soundtracks
  28413. */
  28414. Scene.prototype.disposeSounds = function () {
  28415. if (!this._mainSoundTrack) {
  28416. return;
  28417. }
  28418. this.mainSoundTrack.dispose();
  28419. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28420. this.soundTracks[scIndex].dispose();
  28421. }
  28422. };
  28423. /**
  28424. * Call this function to reduce memory footprint of the scene.
  28425. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28426. */
  28427. Scene.prototype.clearCachedVertexData = function () {
  28428. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28429. var mesh = this.meshes[meshIndex];
  28430. var geometry = mesh.geometry;
  28431. if (geometry) {
  28432. geometry._indices = [];
  28433. for (var vbName in geometry._vertexBuffers) {
  28434. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28435. continue;
  28436. }
  28437. geometry._vertexBuffers[vbName]._buffer._data = null;
  28438. }
  28439. }
  28440. }
  28441. };
  28442. /**
  28443. * This function will remove the local cached buffer data from texture.
  28444. * It will save memory but will prevent the texture from being rebuilt
  28445. */
  28446. Scene.prototype.cleanCachedTextureBuffer = function () {
  28447. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28448. var baseTexture = _a[_i];
  28449. var buffer = baseTexture._buffer;
  28450. if (buffer) {
  28451. baseTexture._buffer = null;
  28452. }
  28453. }
  28454. };
  28455. // Octrees
  28456. /**
  28457. * Get the world extend vectors with an optional filter
  28458. *
  28459. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28460. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28461. */
  28462. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28463. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28464. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28465. filterPredicate = filterPredicate || (function () { return true; });
  28466. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28467. mesh.computeWorldMatrix(true);
  28468. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28469. return;
  28470. }
  28471. var boundingInfo = mesh.getBoundingInfo();
  28472. var minBox = boundingInfo.boundingBox.minimumWorld;
  28473. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28474. BABYLON.Tools.CheckExtends(minBox, min, max);
  28475. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28476. });
  28477. return {
  28478. min: min,
  28479. max: max
  28480. };
  28481. };
  28482. /**
  28483. * Creates or updates the octree used to boost selection (picking)
  28484. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28485. * @param maxCapacity defines the maximum capacity per leaf
  28486. * @param maxDepth defines the maximum depth of the octree
  28487. * @returns an octree of AbstractMesh
  28488. */
  28489. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28490. if (maxCapacity === void 0) { maxCapacity = 64; }
  28491. if (maxDepth === void 0) { maxDepth = 2; }
  28492. if (!this._selectionOctree) {
  28493. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28494. }
  28495. var worldExtends = this.getWorldExtends();
  28496. // Update octree
  28497. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28498. return this._selectionOctree;
  28499. };
  28500. // Picking
  28501. /**
  28502. * Creates a ray that can be used to pick in the scene
  28503. * @param x defines the x coordinate of the origin (on-screen)
  28504. * @param y defines the y coordinate of the origin (on-screen)
  28505. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28506. * @param camera defines the camera to use for the picking
  28507. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28508. * @returns a Ray
  28509. */
  28510. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28511. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28512. var result = BABYLON.Ray.Zero();
  28513. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28514. return result;
  28515. };
  28516. /**
  28517. * Creates a ray that can be used to pick in the scene
  28518. * @param x defines the x coordinate of the origin (on-screen)
  28519. * @param y defines the y coordinate of the origin (on-screen)
  28520. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28521. * @param result defines the ray where to store the picking ray
  28522. * @param camera defines the camera to use for the picking
  28523. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28524. * @returns the current scene
  28525. */
  28526. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28527. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28528. var engine = this._engine;
  28529. if (!camera) {
  28530. if (!this.activeCamera)
  28531. throw new Error("Active camera not set");
  28532. camera = this.activeCamera;
  28533. }
  28534. var cameraViewport = camera.viewport;
  28535. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28536. // Moving coordinates to local viewport world
  28537. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28538. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28539. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28540. return this;
  28541. };
  28542. /**
  28543. * Creates a ray that can be used to pick in the scene
  28544. * @param x defines the x coordinate of the origin (on-screen)
  28545. * @param y defines the y coordinate of the origin (on-screen)
  28546. * @param camera defines the camera to use for the picking
  28547. * @returns a Ray
  28548. */
  28549. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28550. var result = BABYLON.Ray.Zero();
  28551. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28552. return result;
  28553. };
  28554. /**
  28555. * Creates a ray that can be used to pick in the scene
  28556. * @param x defines the x coordinate of the origin (on-screen)
  28557. * @param y defines the y coordinate of the origin (on-screen)
  28558. * @param result defines the ray where to store the picking ray
  28559. * @param camera defines the camera to use for the picking
  28560. * @returns the current scene
  28561. */
  28562. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28563. if (!BABYLON.PickingInfo) {
  28564. return this;
  28565. }
  28566. var engine = this._engine;
  28567. if (!camera) {
  28568. if (!this.activeCamera)
  28569. throw new Error("Active camera not set");
  28570. camera = this.activeCamera;
  28571. }
  28572. var cameraViewport = camera.viewport;
  28573. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28574. var identity = BABYLON.Matrix.Identity();
  28575. // Moving coordinates to local viewport world
  28576. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28577. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28578. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28579. return this;
  28580. };
  28581. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28582. if (!BABYLON.PickingInfo) {
  28583. return null;
  28584. }
  28585. var pickingInfo = null;
  28586. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28587. var mesh = this.meshes[meshIndex];
  28588. if (predicate) {
  28589. if (!predicate(mesh)) {
  28590. continue;
  28591. }
  28592. }
  28593. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28594. continue;
  28595. }
  28596. var world = mesh.getWorldMatrix();
  28597. var ray = rayFunction(world);
  28598. var result = mesh.intersects(ray, fastCheck);
  28599. if (!result || !result.hit)
  28600. continue;
  28601. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28602. continue;
  28603. pickingInfo = result;
  28604. if (fastCheck) {
  28605. break;
  28606. }
  28607. }
  28608. return pickingInfo || new BABYLON.PickingInfo();
  28609. };
  28610. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28611. if (!BABYLON.PickingInfo) {
  28612. return null;
  28613. }
  28614. var pickingInfos = new Array();
  28615. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28616. var mesh = this.meshes[meshIndex];
  28617. if (predicate) {
  28618. if (!predicate(mesh)) {
  28619. continue;
  28620. }
  28621. }
  28622. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28623. continue;
  28624. }
  28625. var world = mesh.getWorldMatrix();
  28626. var ray = rayFunction(world);
  28627. var result = mesh.intersects(ray, false);
  28628. if (!result || !result.hit)
  28629. continue;
  28630. pickingInfos.push(result);
  28631. }
  28632. return pickingInfos;
  28633. };
  28634. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28635. if (!BABYLON.PickingInfo) {
  28636. return null;
  28637. }
  28638. var pickingInfo = null;
  28639. if (!camera) {
  28640. if (!this.activeCamera) {
  28641. return null;
  28642. }
  28643. camera = this.activeCamera;
  28644. }
  28645. if (this.spriteManagers.length > 0) {
  28646. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28647. var spriteManager = this.spriteManagers[spriteIndex];
  28648. if (!spriteManager.isPickable) {
  28649. continue;
  28650. }
  28651. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28652. if (!result || !result.hit)
  28653. continue;
  28654. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28655. continue;
  28656. pickingInfo = result;
  28657. if (fastCheck) {
  28658. break;
  28659. }
  28660. }
  28661. }
  28662. return pickingInfo || new BABYLON.PickingInfo();
  28663. };
  28664. /** Launch a ray to try to pick a mesh in the scene
  28665. * @param x position on screen
  28666. * @param y position on screen
  28667. * @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
  28668. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28669. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28670. * @returns a PickingInfo
  28671. */
  28672. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28673. var _this = this;
  28674. if (!BABYLON.PickingInfo) {
  28675. return null;
  28676. }
  28677. var result = this._internalPick(function (world) {
  28678. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28679. return _this._tempPickingRay;
  28680. }, predicate, fastCheck);
  28681. if (result) {
  28682. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28683. }
  28684. return result;
  28685. };
  28686. /** Launch a ray to try to pick a sprite in the scene
  28687. * @param x position on screen
  28688. * @param y position on screen
  28689. * @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
  28690. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28691. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28692. * @returns a PickingInfo
  28693. */
  28694. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28695. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28696. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28697. };
  28698. /** Use the given ray to pick a mesh in the scene
  28699. * @param ray The ray to use to pick meshes
  28700. * @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
  28701. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28702. * @returns a PickingInfo
  28703. */
  28704. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28705. var _this = this;
  28706. var result = this._internalPick(function (world) {
  28707. if (!_this._pickWithRayInverseMatrix) {
  28708. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28709. }
  28710. world.invertToRef(_this._pickWithRayInverseMatrix);
  28711. if (!_this._cachedRayForTransform) {
  28712. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28713. }
  28714. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28715. return _this._cachedRayForTransform;
  28716. }, predicate, fastCheck);
  28717. if (result) {
  28718. result.ray = ray;
  28719. }
  28720. return result;
  28721. };
  28722. /**
  28723. * Launch a ray to try to pick a mesh in the scene
  28724. * @param x X position on screen
  28725. * @param y Y position on screen
  28726. * @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
  28727. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28728. * @returns an array of PickingInfo
  28729. */
  28730. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28731. var _this = this;
  28732. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28733. };
  28734. /**
  28735. * Launch a ray to try to pick a mesh in the scene
  28736. * @param ray Ray to use
  28737. * @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
  28738. * @returns an array of PickingInfo
  28739. */
  28740. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28741. var _this = this;
  28742. return this._internalMultiPick(function (world) {
  28743. if (!_this._pickWithRayInverseMatrix) {
  28744. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28745. }
  28746. world.invertToRef(_this._pickWithRayInverseMatrix);
  28747. if (!_this._cachedRayForTransform) {
  28748. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28749. }
  28750. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28751. return _this._cachedRayForTransform;
  28752. }, predicate);
  28753. };
  28754. /**
  28755. * Force the value of meshUnderPointer
  28756. * @param mesh defines the mesh to use
  28757. */
  28758. Scene.prototype.setPointerOverMesh = function (mesh) {
  28759. if (this._pointerOverMesh === mesh) {
  28760. return;
  28761. }
  28762. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28763. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28764. }
  28765. this._pointerOverMesh = mesh;
  28766. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28767. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28768. }
  28769. };
  28770. /**
  28771. * Gets the mesh under the pointer
  28772. * @returns a Mesh or null if no mesh is under the pointer
  28773. */
  28774. Scene.prototype.getPointerOverMesh = function () {
  28775. return this._pointerOverMesh;
  28776. };
  28777. /**
  28778. * Force the sprite under the pointer
  28779. * @param sprite defines the sprite to use
  28780. */
  28781. Scene.prototype.setPointerOverSprite = function (sprite) {
  28782. if (this._pointerOverSprite === sprite) {
  28783. return;
  28784. }
  28785. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28786. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28787. }
  28788. this._pointerOverSprite = sprite;
  28789. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28790. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28791. }
  28792. };
  28793. /**
  28794. * Gets the sprite under the pointer
  28795. * @returns a Sprite or null if no sprite is under the pointer
  28796. */
  28797. Scene.prototype.getPointerOverSprite = function () {
  28798. return this._pointerOverSprite;
  28799. };
  28800. // Physics
  28801. /**
  28802. * Gets the current physics engine
  28803. * @returns a PhysicsEngine or null if none attached
  28804. */
  28805. Scene.prototype.getPhysicsEngine = function () {
  28806. return this._physicsEngine;
  28807. };
  28808. /**
  28809. * Enables physics to the current scene
  28810. * @param gravity defines the scene's gravity for the physics engine
  28811. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28812. * @return a boolean indicating if the physics engine was initialized
  28813. */
  28814. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28815. if (gravity === void 0) { gravity = null; }
  28816. if (this._physicsEngine) {
  28817. return true;
  28818. }
  28819. try {
  28820. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28821. return true;
  28822. }
  28823. catch (e) {
  28824. BABYLON.Tools.Error(e.message);
  28825. return false;
  28826. }
  28827. };
  28828. /**
  28829. * Disables and disposes the physics engine associated with the scene
  28830. */
  28831. Scene.prototype.disablePhysicsEngine = function () {
  28832. if (!this._physicsEngine) {
  28833. return;
  28834. }
  28835. this._physicsEngine.dispose();
  28836. this._physicsEngine = null;
  28837. };
  28838. /**
  28839. * Gets a boolean indicating if there is an active physics engine
  28840. * @returns a boolean indicating if there is an active physics engine
  28841. */
  28842. Scene.prototype.isPhysicsEnabled = function () {
  28843. return this._physicsEngine !== undefined;
  28844. };
  28845. /**
  28846. * Deletes a physics compound impostor
  28847. * @param compound defines the compound to delete
  28848. */
  28849. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28850. var mesh = compound.parts[0].mesh;
  28851. if (mesh.physicsImpostor) {
  28852. mesh.physicsImpostor.dispose( /*true*/);
  28853. mesh.physicsImpostor = null;
  28854. }
  28855. };
  28856. // Misc.
  28857. /** @hidden */
  28858. Scene.prototype._rebuildGeometries = function () {
  28859. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28860. var geometry = _a[_i];
  28861. geometry._rebuild();
  28862. }
  28863. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28864. var mesh = _c[_b];
  28865. mesh._rebuild();
  28866. }
  28867. if (this.postProcessManager) {
  28868. this.postProcessManager._rebuild();
  28869. }
  28870. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28871. var layer = _e[_d];
  28872. layer._rebuild();
  28873. }
  28874. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28875. var effectLayer = _g[_f];
  28876. effectLayer._rebuild();
  28877. }
  28878. if (this._boundingBoxRenderer) {
  28879. this._boundingBoxRenderer._rebuild();
  28880. }
  28881. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28882. var system = _j[_h];
  28883. system.rebuild();
  28884. }
  28885. if (this._postProcessRenderPipelineManager) {
  28886. this._postProcessRenderPipelineManager._rebuild();
  28887. }
  28888. };
  28889. /** @hidden */
  28890. Scene.prototype._rebuildTextures = function () {
  28891. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28892. var texture = _a[_i];
  28893. texture._rebuild();
  28894. }
  28895. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28896. };
  28897. /**
  28898. * Creates a default light for the scene.
  28899. * @param replace Whether to replace the existing lights in the scene.
  28900. */
  28901. Scene.prototype.createDefaultLight = function (replace) {
  28902. if (replace === void 0) { replace = false; }
  28903. // Dispose existing light in replace mode.
  28904. if (replace) {
  28905. if (this.lights) {
  28906. for (var i = 0; i < this.lights.length; i++) {
  28907. this.lights[i].dispose();
  28908. }
  28909. }
  28910. }
  28911. // Light
  28912. if (this.lights.length === 0) {
  28913. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28914. }
  28915. };
  28916. /**
  28917. * Creates a default camera for the scene.
  28918. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28919. * @param replace Whether to replace the existing active camera in the scene.
  28920. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28921. */
  28922. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28923. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28924. if (replace === void 0) { replace = false; }
  28925. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28926. // Dispose existing camera in replace mode.
  28927. if (replace) {
  28928. if (this.activeCamera) {
  28929. this.activeCamera.dispose();
  28930. this.activeCamera = null;
  28931. }
  28932. }
  28933. // Camera
  28934. if (!this.activeCamera) {
  28935. var worldExtends = this.getWorldExtends();
  28936. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28937. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28938. var camera;
  28939. var radius = worldSize.length() * 1.5;
  28940. // empty scene scenario!
  28941. if (!isFinite(radius)) {
  28942. radius = 1;
  28943. worldCenter.copyFromFloats(0, 0, 0);
  28944. }
  28945. if (createArcRotateCamera) {
  28946. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28947. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28948. arcRotateCamera.wheelPrecision = 100 / radius;
  28949. camera = arcRotateCamera;
  28950. }
  28951. else {
  28952. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28953. freeCamera.setTarget(worldCenter);
  28954. camera = freeCamera;
  28955. }
  28956. camera.minZ = radius * 0.01;
  28957. camera.maxZ = radius * 1000;
  28958. camera.speed = radius * 0.2;
  28959. this.activeCamera = camera;
  28960. var canvas = this.getEngine().getRenderingCanvas();
  28961. if (attachCameraControls && canvas) {
  28962. camera.attachControl(canvas);
  28963. }
  28964. }
  28965. };
  28966. /**
  28967. * Creates a default camera and a default light
  28968. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28969. * @param replace defines if the camera and/or light will replace the existing ones
  28970. * @param attachCameraControls defines if attachControl will be called on the new camera
  28971. */
  28972. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28973. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28974. if (replace === void 0) { replace = false; }
  28975. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28976. this.createDefaultLight(replace);
  28977. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28978. };
  28979. /**
  28980. * Creates a new sky box
  28981. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28982. * @param environmentTexture defines the texture to use as environment texture
  28983. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28984. * @param scale defines the overall scale of the skybox
  28985. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28986. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28987. * @returns a new mesh holding the sky box
  28988. */
  28989. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28990. if (pbr === void 0) { pbr = false; }
  28991. if (scale === void 0) { scale = 1000; }
  28992. if (blur === void 0) { blur = 0; }
  28993. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28994. if (!environmentTexture) {
  28995. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28996. return null;
  28997. }
  28998. if (setGlobalEnvTexture) {
  28999. if (environmentTexture) {
  29000. this.environmentTexture = environmentTexture;
  29001. }
  29002. }
  29003. // Skybox
  29004. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  29005. if (pbr) {
  29006. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  29007. hdrSkyboxMaterial.backFaceCulling = false;
  29008. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  29009. if (hdrSkyboxMaterial.reflectionTexture) {
  29010. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29011. }
  29012. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  29013. hdrSkyboxMaterial.disableLighting = true;
  29014. hdrSkyboxMaterial.twoSidedLighting = true;
  29015. hdrSkybox.infiniteDistance = true;
  29016. hdrSkybox.material = hdrSkyboxMaterial;
  29017. }
  29018. else {
  29019. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  29020. skyboxMaterial.backFaceCulling = false;
  29021. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  29022. if (skyboxMaterial.reflectionTexture) {
  29023. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29024. }
  29025. skyboxMaterial.disableLighting = true;
  29026. hdrSkybox.infiniteDistance = true;
  29027. hdrSkybox.material = skyboxMaterial;
  29028. }
  29029. return hdrSkybox;
  29030. };
  29031. /**
  29032. * Creates a new environment
  29033. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29034. * @param options defines the options you can use to configure the environment
  29035. * @returns the new EnvironmentHelper
  29036. */
  29037. Scene.prototype.createDefaultEnvironment = function (options) {
  29038. if (BABYLON.EnvironmentHelper) {
  29039. return new BABYLON.EnvironmentHelper(options, this);
  29040. }
  29041. return null;
  29042. };
  29043. /**
  29044. * Creates a new VREXperienceHelper
  29045. * @see http://doc.babylonjs.com/how_to/webvr_helper
  29046. * @param webVROptions defines the options used to create the new VREXperienceHelper
  29047. * @returns a new VREXperienceHelper
  29048. */
  29049. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  29050. if (webVROptions === void 0) { webVROptions = {}; }
  29051. return new BABYLON.VRExperienceHelper(this, webVROptions);
  29052. };
  29053. // Tags
  29054. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29055. if (tagsQuery === undefined) {
  29056. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29057. return list;
  29058. }
  29059. var listByTags = [];
  29060. forEach = forEach || (function (item) { return; });
  29061. for (var i in list) {
  29062. var item = list[i];
  29063. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29064. listByTags.push(item);
  29065. forEach(item);
  29066. }
  29067. }
  29068. return listByTags;
  29069. };
  29070. /**
  29071. * Get a list of meshes by tags
  29072. * @param tagsQuery defines the tags query to use
  29073. * @param forEach defines a predicate used to filter results
  29074. * @returns an array of Mesh
  29075. */
  29076. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29077. return this._getByTags(this.meshes, tagsQuery, forEach);
  29078. };
  29079. /**
  29080. * Get a list of cameras by tags
  29081. * @param tagsQuery defines the tags query to use
  29082. * @param forEach defines a predicate used to filter results
  29083. * @returns an array of Camera
  29084. */
  29085. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29086. return this._getByTags(this.cameras, tagsQuery, forEach);
  29087. };
  29088. /**
  29089. * Get a list of lights by tags
  29090. * @param tagsQuery defines the tags query to use
  29091. * @param forEach defines a predicate used to filter results
  29092. * @returns an array of Light
  29093. */
  29094. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29095. return this._getByTags(this.lights, tagsQuery, forEach);
  29096. };
  29097. /**
  29098. * Get a list of materials by tags
  29099. * @param tagsQuery defines the tags query to use
  29100. * @param forEach defines a predicate used to filter results
  29101. * @returns an array of Material
  29102. */
  29103. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29104. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29105. };
  29106. /**
  29107. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29108. * This allowed control for front to back rendering or reversly depending of the special needs.
  29109. *
  29110. * @param renderingGroupId The rendering group id corresponding to its index
  29111. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29112. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29113. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29114. */
  29115. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29116. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29117. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29118. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29119. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29120. };
  29121. /**
  29122. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29123. *
  29124. * @param renderingGroupId The rendering group id corresponding to its index
  29125. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29126. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29127. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29128. */
  29129. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29130. if (depth === void 0) { depth = true; }
  29131. if (stencil === void 0) { stencil = true; }
  29132. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29133. };
  29134. /**
  29135. * Will flag all materials as dirty to trigger new shader compilation
  29136. * @param flag defines the flag used to specify which material part must be marked as dirty
  29137. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29138. */
  29139. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29140. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29141. var material = _a[_i];
  29142. if (predicate && !predicate(material)) {
  29143. continue;
  29144. }
  29145. material.markAsDirty(flag);
  29146. }
  29147. };
  29148. /** @hidden */
  29149. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29150. var _this = this;
  29151. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29152. this._activeRequests.push(request);
  29153. request.onCompleteObservable.add(function (request) {
  29154. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29155. });
  29156. return request;
  29157. };
  29158. /** @hidden */
  29159. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29160. var _this = this;
  29161. return new Promise(function (resolve, reject) {
  29162. _this._loadFile(url, function (data) {
  29163. resolve(data);
  29164. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29165. reject(exception);
  29166. });
  29167. });
  29168. };
  29169. // Statics
  29170. Scene._FOGMODE_NONE = 0;
  29171. Scene._FOGMODE_EXP = 1;
  29172. Scene._FOGMODE_EXP2 = 2;
  29173. Scene._FOGMODE_LINEAR = 3;
  29174. Scene._uniqueIdCounter = 0;
  29175. /**
  29176. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29177. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29178. */
  29179. Scene.MinDeltaTime = 1.0;
  29180. /**
  29181. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29182. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29183. */
  29184. Scene.MaxDeltaTime = 1000.0;
  29185. /** The distance in pixel that you have to move to prevent some events */
  29186. Scene.DragMovementThreshold = 10; // in pixels
  29187. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29188. Scene.LongPressDelay = 500; // in milliseconds
  29189. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29190. Scene.DoubleClickDelay = 300; // in milliseconds
  29191. /** If you need to check double click without raising a single click at first click, enable this flag */
  29192. Scene.ExclusiveDoubleClickMode = false;
  29193. return Scene;
  29194. }());
  29195. BABYLON.Scene = Scene;
  29196. })(BABYLON || (BABYLON = {}));
  29197. //# sourceMappingURL=babylon.scene.js.map
  29198. var BABYLON;
  29199. (function (BABYLON) {
  29200. /**
  29201. * Set of assets to keep when moving a scene into an asset container.
  29202. */
  29203. var KeepAssets = /** @class */ (function () {
  29204. function KeepAssets() {
  29205. /**
  29206. * Cameras to keep.
  29207. */
  29208. this.cameras = new Array();
  29209. /**
  29210. * Lights to keep.
  29211. */
  29212. this.lights = new Array();
  29213. /**
  29214. * Meshes to keep.
  29215. */
  29216. this.meshes = new Array();
  29217. /**
  29218. * Skeletons to keep.
  29219. */
  29220. this.skeletons = new Array();
  29221. /**
  29222. * ParticleSystems to keep.
  29223. */
  29224. this.particleSystems = new Array();
  29225. /**
  29226. * Animations to keep.
  29227. */
  29228. this.animations = new Array();
  29229. /**
  29230. * AnimationGroups to keep.
  29231. */
  29232. this.animationGroups = new Array();
  29233. /**
  29234. * MultiMaterials to keep.
  29235. */
  29236. this.multiMaterials = new Array();
  29237. /**
  29238. * Materials to keep.
  29239. */
  29240. this.materials = new Array();
  29241. /**
  29242. * MorphTargetManagers to keep.
  29243. */
  29244. this.morphTargetManagers = new Array();
  29245. /**
  29246. * Geometries to keep.
  29247. */
  29248. this.geometries = new Array();
  29249. /**
  29250. * TransformNodes to keep.
  29251. */
  29252. this.transformNodes = new Array();
  29253. /**
  29254. * LensFlareSystems to keep.
  29255. */
  29256. this.lensFlareSystems = new Array();
  29257. /**
  29258. * ShadowGenerators to keep.
  29259. */
  29260. this.shadowGenerators = new Array();
  29261. /**
  29262. * ActionManagers to keep.
  29263. */
  29264. this.actionManagers = new Array();
  29265. /**
  29266. * Sounds to keep.
  29267. */
  29268. this.sounds = new Array();
  29269. /**
  29270. * Textures to keep.
  29271. */
  29272. this.textures = new Array();
  29273. /**
  29274. * Effect layers to keep.
  29275. */
  29276. this.effectLayers = new Array();
  29277. }
  29278. return KeepAssets;
  29279. }());
  29280. BABYLON.KeepAssets = KeepAssets;
  29281. /**
  29282. * Container with a set of assets that can be added or removed from a scene.
  29283. */
  29284. var AssetContainer = /** @class */ (function () {
  29285. /**
  29286. * Instantiates an AssetContainer.
  29287. * @param scene The scene the AssetContainer belongs to.
  29288. */
  29289. function AssetContainer(scene) {
  29290. // Objects
  29291. /**
  29292. * Cameras populated in the container.
  29293. */
  29294. this.cameras = new Array();
  29295. /**
  29296. * Lights populated in the container.
  29297. */
  29298. this.lights = new Array();
  29299. /**
  29300. * Meshes populated in the container.
  29301. */
  29302. this.meshes = new Array();
  29303. /**
  29304. * Skeletons populated in the container.
  29305. */
  29306. this.skeletons = new Array();
  29307. /**
  29308. * ParticleSystems populated in the container.
  29309. */
  29310. this.particleSystems = new Array();
  29311. /**
  29312. * Animations populated in the container.
  29313. */
  29314. this.animations = new Array();
  29315. /**
  29316. * AnimationGroups populated in the container.
  29317. */
  29318. this.animationGroups = new Array();
  29319. /**
  29320. * MultiMaterials populated in the container.
  29321. */
  29322. this.multiMaterials = new Array();
  29323. /**
  29324. * Materials populated in the container.
  29325. */
  29326. this.materials = new Array();
  29327. /**
  29328. * MorphTargetManagers populated in the container.
  29329. */
  29330. this.morphTargetManagers = new Array();
  29331. /**
  29332. * Geometries populated in the container.
  29333. */
  29334. this.geometries = new Array();
  29335. /**
  29336. * TransformNodes populated in the container.
  29337. */
  29338. this.transformNodes = new Array();
  29339. /**
  29340. * LensFlareSystems populated in the container.
  29341. */
  29342. this.lensFlareSystems = new Array();
  29343. /**
  29344. * ShadowGenerators populated in the container.
  29345. */
  29346. this.shadowGenerators = new Array();
  29347. /**
  29348. * ActionManagers populated in the container.
  29349. */
  29350. this.actionManagers = new Array();
  29351. /**
  29352. * Sounds populated in the container.
  29353. */
  29354. this.sounds = new Array();
  29355. /**
  29356. * Textures populated in the container.
  29357. */
  29358. this.textures = new Array();
  29359. /**
  29360. * Effect layers populated in the container.
  29361. */
  29362. this.effectLayers = new Array();
  29363. this.scene = scene;
  29364. }
  29365. /**
  29366. * Adds all the assets from the container to the scene.
  29367. */
  29368. AssetContainer.prototype.addAllToScene = function () {
  29369. var _this = this;
  29370. this.cameras.forEach(function (o) {
  29371. _this.scene.addCamera(o);
  29372. });
  29373. this.lights.forEach(function (o) {
  29374. _this.scene.addLight(o);
  29375. });
  29376. this.meshes.forEach(function (o) {
  29377. _this.scene.addMesh(o);
  29378. });
  29379. this.skeletons.forEach(function (o) {
  29380. _this.scene.addSkeleton(o);
  29381. });
  29382. this.particleSystems.forEach(function (o) {
  29383. _this.scene.addParticleSystem(o);
  29384. });
  29385. this.animations.forEach(function (o) {
  29386. _this.scene.addAnimation(o);
  29387. });
  29388. this.animationGroups.forEach(function (o) {
  29389. _this.scene.addAnimationGroup(o);
  29390. });
  29391. this.multiMaterials.forEach(function (o) {
  29392. _this.scene.addMultiMaterial(o);
  29393. });
  29394. this.materials.forEach(function (o) {
  29395. _this.scene.addMaterial(o);
  29396. });
  29397. this.morphTargetManagers.forEach(function (o) {
  29398. _this.scene.addMorphTargetManager(o);
  29399. });
  29400. this.geometries.forEach(function (o) {
  29401. _this.scene.addGeometry(o);
  29402. });
  29403. this.transformNodes.forEach(function (o) {
  29404. _this.scene.addTransformNode(o);
  29405. });
  29406. this.lensFlareSystems.forEach(function (o) {
  29407. _this.scene.addLensFlareSystem(o);
  29408. });
  29409. this.actionManagers.forEach(function (o) {
  29410. _this.scene.addActionManager(o);
  29411. });
  29412. this.sounds.forEach(function (o) {
  29413. o.play();
  29414. o.autoplay = true;
  29415. _this.scene.mainSoundTrack.AddSound(o);
  29416. });
  29417. this.textures.forEach(function (o) {
  29418. _this.scene.addTexture(o);
  29419. });
  29420. this.effectLayers.forEach(function (o) {
  29421. _this.scene.addEffectLayer(o);
  29422. });
  29423. };
  29424. /**
  29425. * Removes all the assets in the container from the scene
  29426. */
  29427. AssetContainer.prototype.removeAllFromScene = function () {
  29428. var _this = this;
  29429. this.cameras.forEach(function (o) {
  29430. _this.scene.removeCamera(o);
  29431. });
  29432. this.lights.forEach(function (o) {
  29433. _this.scene.removeLight(o);
  29434. });
  29435. this.meshes.forEach(function (o) {
  29436. _this.scene.removeMesh(o);
  29437. });
  29438. this.skeletons.forEach(function (o) {
  29439. _this.scene.removeSkeleton(o);
  29440. });
  29441. this.particleSystems.forEach(function (o) {
  29442. _this.scene.removeParticleSystem(o);
  29443. });
  29444. this.animations.forEach(function (o) {
  29445. _this.scene.removeAnimation(o);
  29446. });
  29447. this.animationGroups.forEach(function (o) {
  29448. _this.scene.removeAnimationGroup(o);
  29449. });
  29450. this.multiMaterials.forEach(function (o) {
  29451. _this.scene.removeMultiMaterial(o);
  29452. });
  29453. this.materials.forEach(function (o) {
  29454. _this.scene.removeMaterial(o);
  29455. });
  29456. this.morphTargetManagers.forEach(function (o) {
  29457. _this.scene.removeMorphTargetManager(o);
  29458. });
  29459. this.geometries.forEach(function (o) {
  29460. _this.scene.removeGeometry(o);
  29461. });
  29462. this.transformNodes.forEach(function (o) {
  29463. _this.scene.removeTransformNode(o);
  29464. });
  29465. this.lensFlareSystems.forEach(function (o) {
  29466. _this.scene.removeLensFlareSystem(o);
  29467. });
  29468. this.actionManagers.forEach(function (o) {
  29469. _this.scene.removeActionManager(o);
  29470. });
  29471. this.sounds.forEach(function (o) {
  29472. o.stop();
  29473. o.autoplay = false;
  29474. _this.scene.mainSoundTrack.RemoveSound(o);
  29475. });
  29476. this.textures.forEach(function (o) {
  29477. _this.scene.removeTexture(o);
  29478. });
  29479. this.effectLayers.forEach(function (o) {
  29480. _this.scene.removeEffectLayer(o);
  29481. });
  29482. };
  29483. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29484. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29485. var asset = sourceAssets_1[_i];
  29486. var move = true;
  29487. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29488. var keepAsset = keepAssets_1[_a];
  29489. if (asset === keepAsset) {
  29490. move = false;
  29491. break;
  29492. }
  29493. }
  29494. if (move) {
  29495. targetAssets.push(asset);
  29496. }
  29497. }
  29498. };
  29499. /**
  29500. * Removes all the assets contained in the scene and adds them to the container.
  29501. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29502. */
  29503. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29504. if (keepAssets === undefined) {
  29505. keepAssets = new KeepAssets();
  29506. }
  29507. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29508. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29509. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29510. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29511. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29512. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29513. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29514. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29515. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29516. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29517. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29518. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29519. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29520. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29521. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29522. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29523. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29524. this.removeAllFromScene();
  29525. };
  29526. /**
  29527. * 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.
  29528. * @returns the root mesh
  29529. */
  29530. AssetContainer.prototype.createRootMesh = function () {
  29531. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29532. this.meshes.forEach(function (m) {
  29533. if (!m.parent) {
  29534. rootMesh.addChild(m);
  29535. }
  29536. });
  29537. this.meshes.unshift(rootMesh);
  29538. return rootMesh;
  29539. };
  29540. return AssetContainer;
  29541. }());
  29542. BABYLON.AssetContainer = AssetContainer;
  29543. })(BABYLON || (BABYLON = {}));
  29544. //# sourceMappingURL=babylon.assetContainer.js.map
  29545. var BABYLON;
  29546. (function (BABYLON) {
  29547. var Buffer = /** @class */ (function () {
  29548. /**
  29549. * Constructor
  29550. * @param engine the engine
  29551. * @param data the data to use for this buffer
  29552. * @param updatable whether the data is updatable
  29553. * @param stride the stride (optional)
  29554. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29555. * @param instanced whether the buffer is instanced (optional)
  29556. * @param useBytes set to true if the stride in in bytes (optional)
  29557. */
  29558. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29559. if (stride === void 0) { stride = 0; }
  29560. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29561. if (instanced === void 0) { instanced = false; }
  29562. if (useBytes === void 0) { useBytes = false; }
  29563. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29564. this._engine = engine.getScene().getEngine();
  29565. }
  29566. else {
  29567. this._engine = engine;
  29568. }
  29569. this._updatable = updatable;
  29570. this._instanced = instanced;
  29571. this._data = data;
  29572. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29573. if (!postponeInternalCreation) { // by default
  29574. this.create();
  29575. }
  29576. }
  29577. /**
  29578. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29579. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29580. * @param offset defines offset in the buffer (0 by default)
  29581. * @param size defines the size in floats of attributes (position is 3 for instance)
  29582. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29583. * @param instanced defines if the vertex buffer contains indexed data
  29584. * @param useBytes defines if the offset and stride are in bytes
  29585. * @returns the new vertex buffer
  29586. */
  29587. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29588. if (useBytes === void 0) { useBytes = false; }
  29589. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29590. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29591. // a lot of these parameters are ignored as they are overriden by the buffer
  29592. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29593. };
  29594. // Properties
  29595. Buffer.prototype.isUpdatable = function () {
  29596. return this._updatable;
  29597. };
  29598. Buffer.prototype.getData = function () {
  29599. return this._data;
  29600. };
  29601. Buffer.prototype.getBuffer = function () {
  29602. return this._buffer;
  29603. };
  29604. /**
  29605. * Gets the stride in float32 units (i.e. byte stride / 4).
  29606. * May not be an integer if the byte stride is not divisible by 4.
  29607. * DEPRECATED. Use byteStride instead.
  29608. * @returns the stride in float32 units
  29609. */
  29610. Buffer.prototype.getStrideSize = function () {
  29611. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29612. };
  29613. // Methods
  29614. Buffer.prototype.create = function (data) {
  29615. if (data === void 0) { data = null; }
  29616. if (!data && this._buffer) {
  29617. return; // nothing to do
  29618. }
  29619. data = data || this._data;
  29620. if (!data) {
  29621. return;
  29622. }
  29623. if (!this._buffer) { // create buffer
  29624. if (this._updatable) {
  29625. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29626. this._data = data;
  29627. }
  29628. else {
  29629. this._buffer = this._engine.createVertexBuffer(data);
  29630. }
  29631. }
  29632. else if (this._updatable) { // update buffer
  29633. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29634. this._data = data;
  29635. }
  29636. };
  29637. Buffer.prototype._rebuild = function () {
  29638. this._buffer = null;
  29639. this.create(this._data);
  29640. };
  29641. Buffer.prototype.update = function (data) {
  29642. this.create(data);
  29643. };
  29644. /**
  29645. * Updates the data directly.
  29646. * @param data the new data
  29647. * @param offset the new offset
  29648. * @param vertexCount the vertex count (optional)
  29649. * @param useBytes set to true if the offset is in bytes
  29650. */
  29651. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29652. if (useBytes === void 0) { useBytes = false; }
  29653. if (!this._buffer) {
  29654. return;
  29655. }
  29656. if (this._updatable) { // update buffer
  29657. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29658. this._data = null;
  29659. }
  29660. };
  29661. Buffer.prototype.dispose = function () {
  29662. if (!this._buffer) {
  29663. return;
  29664. }
  29665. if (this._engine._releaseBuffer(this._buffer)) {
  29666. this._buffer = null;
  29667. }
  29668. };
  29669. return Buffer;
  29670. }());
  29671. BABYLON.Buffer = Buffer;
  29672. })(BABYLON || (BABYLON = {}));
  29673. //# sourceMappingURL=babylon.buffer.js.map
  29674. var BABYLON;
  29675. (function (BABYLON) {
  29676. var VertexBuffer = /** @class */ (function () {
  29677. /**
  29678. * Constructor
  29679. * @param engine the engine
  29680. * @param data the data to use for this vertex buffer
  29681. * @param kind the vertex buffer kind
  29682. * @param updatable whether the data is updatable
  29683. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29684. * @param stride the stride (optional)
  29685. * @param instanced whether the buffer is instanced (optional)
  29686. * @param offset the offset of the data (optional)
  29687. * @param size the number of components (optional)
  29688. * @param type the type of the component (optional)
  29689. * @param normalized whether the data contains normalized data (optional)
  29690. * @param useBytes set to true if stride and offset are in bytes (optional)
  29691. */
  29692. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29693. if (normalized === void 0) { normalized = false; }
  29694. if (useBytes === void 0) { useBytes = false; }
  29695. if (data instanceof BABYLON.Buffer) {
  29696. this._buffer = data;
  29697. this._ownsBuffer = false;
  29698. }
  29699. else {
  29700. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29701. this._ownsBuffer = true;
  29702. }
  29703. this._kind = kind;
  29704. if (type == undefined) {
  29705. var data_1 = this.getData();
  29706. this.type = VertexBuffer.FLOAT;
  29707. if (data_1 instanceof Int8Array)
  29708. this.type = VertexBuffer.BYTE;
  29709. else if (data_1 instanceof Uint8Array)
  29710. this.type = VertexBuffer.UNSIGNED_BYTE;
  29711. else if (data_1 instanceof Int16Array)
  29712. this.type = VertexBuffer.SHORT;
  29713. else if (data_1 instanceof Uint16Array)
  29714. this.type = VertexBuffer.UNSIGNED_SHORT;
  29715. else if (data_1 instanceof Int32Array)
  29716. this.type = VertexBuffer.INT;
  29717. else if (data_1 instanceof Uint32Array)
  29718. this.type = VertexBuffer.UNSIGNED_INT;
  29719. }
  29720. else {
  29721. this.type = type;
  29722. }
  29723. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29724. if (useBytes) {
  29725. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29726. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29727. this.byteOffset = offset || 0;
  29728. }
  29729. else {
  29730. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29731. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29732. this.byteOffset = (offset || 0) * typeByteLength;
  29733. }
  29734. this.normalized = normalized;
  29735. this._instanced = instanced !== undefined ? instanced : false;
  29736. this._instanceDivisor = instanced ? 1 : 0;
  29737. }
  29738. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29739. /**
  29740. * Gets or sets the instance divisor when in instanced mode
  29741. */
  29742. get: function () {
  29743. return this._instanceDivisor;
  29744. },
  29745. set: function (value) {
  29746. this._instanceDivisor = value;
  29747. if (value == 0) {
  29748. this._instanced = false;
  29749. }
  29750. else {
  29751. this._instanced = true;
  29752. }
  29753. },
  29754. enumerable: true,
  29755. configurable: true
  29756. });
  29757. VertexBuffer.prototype._rebuild = function () {
  29758. if (!this._buffer) {
  29759. return;
  29760. }
  29761. this._buffer._rebuild();
  29762. };
  29763. /**
  29764. * Returns the kind of the VertexBuffer (string).
  29765. */
  29766. VertexBuffer.prototype.getKind = function () {
  29767. return this._kind;
  29768. };
  29769. // Properties
  29770. /**
  29771. * Boolean : is the VertexBuffer updatable ?
  29772. */
  29773. VertexBuffer.prototype.isUpdatable = function () {
  29774. return this._buffer.isUpdatable();
  29775. };
  29776. /**
  29777. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29778. */
  29779. VertexBuffer.prototype.getData = function () {
  29780. return this._buffer.getData();
  29781. };
  29782. /**
  29783. * Returns the WebGLBuffer associated to the VertexBuffer.
  29784. */
  29785. VertexBuffer.prototype.getBuffer = function () {
  29786. return this._buffer.getBuffer();
  29787. };
  29788. /**
  29789. * Returns the stride as a multiple of the type byte length.
  29790. * DEPRECATED. Use byteStride instead.
  29791. */
  29792. VertexBuffer.prototype.getStrideSize = function () {
  29793. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29794. };
  29795. /**
  29796. * Returns the offset as a multiple of the type byte length.
  29797. * DEPRECATED. Use byteOffset instead.
  29798. */
  29799. VertexBuffer.prototype.getOffset = function () {
  29800. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29801. };
  29802. /**
  29803. * Returns the number of components per vertex attribute (integer).
  29804. */
  29805. VertexBuffer.prototype.getSize = function () {
  29806. return this._size;
  29807. };
  29808. /**
  29809. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29810. */
  29811. VertexBuffer.prototype.getIsInstanced = function () {
  29812. return this._instanced;
  29813. };
  29814. /**
  29815. * Returns the instancing divisor, zero for non-instanced (integer).
  29816. */
  29817. VertexBuffer.prototype.getInstanceDivisor = function () {
  29818. return this._instanceDivisor;
  29819. };
  29820. // Methods
  29821. /**
  29822. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29823. * Returns the created WebGLBuffer.
  29824. */
  29825. VertexBuffer.prototype.create = function (data) {
  29826. return this._buffer.create(data);
  29827. };
  29828. /**
  29829. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29830. * This function will create a new buffer if the current one is not updatable
  29831. * Returns the updated WebGLBuffer.
  29832. */
  29833. VertexBuffer.prototype.update = function (data) {
  29834. return this._buffer.update(data);
  29835. };
  29836. /**
  29837. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29838. * Returns the directly updated WebGLBuffer.
  29839. * @param data the new data
  29840. * @param offset the new offset
  29841. * @param useBytes set to true if the offset is in bytes
  29842. */
  29843. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29844. if (useBytes === void 0) { useBytes = false; }
  29845. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29846. };
  29847. /**
  29848. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29849. */
  29850. VertexBuffer.prototype.dispose = function () {
  29851. if (this._ownsBuffer) {
  29852. this._buffer.dispose();
  29853. }
  29854. };
  29855. /**
  29856. * Enumerates each value of this vertex buffer as numbers.
  29857. * @param count the number of values to enumerate
  29858. * @param callback the callback function called for each value
  29859. */
  29860. VertexBuffer.prototype.forEach = function (count, callback) {
  29861. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29862. };
  29863. Object.defineProperty(VertexBuffer, "PositionKind", {
  29864. get: function () {
  29865. return VertexBuffer._PositionKind;
  29866. },
  29867. enumerable: true,
  29868. configurable: true
  29869. });
  29870. Object.defineProperty(VertexBuffer, "NormalKind", {
  29871. get: function () {
  29872. return VertexBuffer._NormalKind;
  29873. },
  29874. enumerable: true,
  29875. configurable: true
  29876. });
  29877. Object.defineProperty(VertexBuffer, "TangentKind", {
  29878. get: function () {
  29879. return VertexBuffer._TangentKind;
  29880. },
  29881. enumerable: true,
  29882. configurable: true
  29883. });
  29884. Object.defineProperty(VertexBuffer, "UVKind", {
  29885. get: function () {
  29886. return VertexBuffer._UVKind;
  29887. },
  29888. enumerable: true,
  29889. configurable: true
  29890. });
  29891. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29892. get: function () {
  29893. return VertexBuffer._UV2Kind;
  29894. },
  29895. enumerable: true,
  29896. configurable: true
  29897. });
  29898. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29899. get: function () {
  29900. return VertexBuffer._UV3Kind;
  29901. },
  29902. enumerable: true,
  29903. configurable: true
  29904. });
  29905. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29906. get: function () {
  29907. return VertexBuffer._UV4Kind;
  29908. },
  29909. enumerable: true,
  29910. configurable: true
  29911. });
  29912. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29913. get: function () {
  29914. return VertexBuffer._UV5Kind;
  29915. },
  29916. enumerable: true,
  29917. configurable: true
  29918. });
  29919. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29920. get: function () {
  29921. return VertexBuffer._UV6Kind;
  29922. },
  29923. enumerable: true,
  29924. configurable: true
  29925. });
  29926. Object.defineProperty(VertexBuffer, "ColorKind", {
  29927. get: function () {
  29928. return VertexBuffer._ColorKind;
  29929. },
  29930. enumerable: true,
  29931. configurable: true
  29932. });
  29933. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29934. get: function () {
  29935. return VertexBuffer._MatricesIndicesKind;
  29936. },
  29937. enumerable: true,
  29938. configurable: true
  29939. });
  29940. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29941. get: function () {
  29942. return VertexBuffer._MatricesWeightsKind;
  29943. },
  29944. enumerable: true,
  29945. configurable: true
  29946. });
  29947. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29948. get: function () {
  29949. return VertexBuffer._MatricesIndicesExtraKind;
  29950. },
  29951. enumerable: true,
  29952. configurable: true
  29953. });
  29954. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29955. get: function () {
  29956. return VertexBuffer._MatricesWeightsExtraKind;
  29957. },
  29958. enumerable: true,
  29959. configurable: true
  29960. });
  29961. /**
  29962. * Deduces the stride given a kind.
  29963. * @param kind The kind string to deduce
  29964. * @returns The deduced stride
  29965. */
  29966. VertexBuffer.DeduceStride = function (kind) {
  29967. switch (kind) {
  29968. case VertexBuffer.UVKind:
  29969. case VertexBuffer.UV2Kind:
  29970. case VertexBuffer.UV3Kind:
  29971. case VertexBuffer.UV4Kind:
  29972. case VertexBuffer.UV5Kind:
  29973. case VertexBuffer.UV6Kind:
  29974. return 2;
  29975. case VertexBuffer.NormalKind:
  29976. case VertexBuffer.PositionKind:
  29977. return 3;
  29978. case VertexBuffer.ColorKind:
  29979. case VertexBuffer.MatricesIndicesKind:
  29980. case VertexBuffer.MatricesIndicesExtraKind:
  29981. case VertexBuffer.MatricesWeightsKind:
  29982. case VertexBuffer.MatricesWeightsExtraKind:
  29983. case VertexBuffer.TangentKind:
  29984. return 4;
  29985. default:
  29986. throw new Error("Invalid kind '" + kind + "'");
  29987. }
  29988. };
  29989. /**
  29990. * Gets the byte length of the given type.
  29991. * @param type the type
  29992. * @returns the number of bytes
  29993. */
  29994. VertexBuffer.GetTypeByteLength = function (type) {
  29995. switch (type) {
  29996. case VertexBuffer.BYTE:
  29997. case VertexBuffer.UNSIGNED_BYTE:
  29998. return 1;
  29999. case VertexBuffer.SHORT:
  30000. case VertexBuffer.UNSIGNED_SHORT:
  30001. return 2;
  30002. case VertexBuffer.INT:
  30003. case VertexBuffer.FLOAT:
  30004. return 4;
  30005. default:
  30006. throw new Error("Invalid type '" + type + "'");
  30007. }
  30008. };
  30009. /**
  30010. * Enumerates each value of the given parameters as numbers.
  30011. * @param data the data to enumerate
  30012. * @param byteOffset the byte offset of the data
  30013. * @param byteStride the byte stride of the data
  30014. * @param componentCount the number of components per element
  30015. * @param componentType the type of the component
  30016. * @param count the total number of components
  30017. * @param normalized whether the data is normalized
  30018. * @param callback the callback function called for each value
  30019. */
  30020. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30021. if (data instanceof Array) {
  30022. var offset = byteOffset / 4;
  30023. var stride = byteStride / 4;
  30024. for (var index = 0; index < count; index += componentCount) {
  30025. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30026. callback(data[offset + componentIndex], index + componentIndex);
  30027. }
  30028. offset += stride;
  30029. }
  30030. }
  30031. else {
  30032. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30033. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30034. for (var index = 0; index < count; index += componentCount) {
  30035. var componentByteOffset = byteOffset;
  30036. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30037. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30038. callback(value, index + componentIndex);
  30039. componentByteOffset += componentByteLength;
  30040. }
  30041. byteOffset += byteStride;
  30042. }
  30043. }
  30044. };
  30045. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30046. switch (type) {
  30047. case VertexBuffer.BYTE: {
  30048. var value = dataView.getInt8(byteOffset);
  30049. if (normalized) {
  30050. value = Math.max(value / 127, -1);
  30051. }
  30052. return value;
  30053. }
  30054. case VertexBuffer.UNSIGNED_BYTE: {
  30055. var value = dataView.getUint8(byteOffset);
  30056. if (normalized) {
  30057. value = value / 255;
  30058. }
  30059. return value;
  30060. }
  30061. case VertexBuffer.SHORT: {
  30062. var value = dataView.getInt16(byteOffset, true);
  30063. if (normalized) {
  30064. value = Math.max(value / 16383, -1);
  30065. }
  30066. return value;
  30067. }
  30068. case VertexBuffer.UNSIGNED_SHORT: {
  30069. var value = dataView.getUint16(byteOffset, true);
  30070. if (normalized) {
  30071. value = value / 65535;
  30072. }
  30073. return value;
  30074. }
  30075. case VertexBuffer.FLOAT: {
  30076. return dataView.getFloat32(byteOffset, true);
  30077. }
  30078. default: {
  30079. throw new Error("Invalid component type " + type);
  30080. }
  30081. }
  30082. };
  30083. /**
  30084. * The byte type.
  30085. */
  30086. VertexBuffer.BYTE = 5120;
  30087. /**
  30088. * The unsigned byte type.
  30089. */
  30090. VertexBuffer.UNSIGNED_BYTE = 5121;
  30091. /**
  30092. * The short type.
  30093. */
  30094. VertexBuffer.SHORT = 5122;
  30095. /**
  30096. * The unsigned short type.
  30097. */
  30098. VertexBuffer.UNSIGNED_SHORT = 5123;
  30099. /**
  30100. * The integer type.
  30101. */
  30102. VertexBuffer.INT = 5124;
  30103. /**
  30104. * The unsigned integer type.
  30105. */
  30106. VertexBuffer.UNSIGNED_INT = 5125;
  30107. /**
  30108. * The float type.
  30109. */
  30110. VertexBuffer.FLOAT = 5126;
  30111. // Enums
  30112. VertexBuffer._PositionKind = "position";
  30113. VertexBuffer._NormalKind = "normal";
  30114. VertexBuffer._TangentKind = "tangent";
  30115. VertexBuffer._UVKind = "uv";
  30116. VertexBuffer._UV2Kind = "uv2";
  30117. VertexBuffer._UV3Kind = "uv3";
  30118. VertexBuffer._UV4Kind = "uv4";
  30119. VertexBuffer._UV5Kind = "uv5";
  30120. VertexBuffer._UV6Kind = "uv6";
  30121. VertexBuffer._ColorKind = "color";
  30122. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30123. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30124. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30125. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30126. return VertexBuffer;
  30127. }());
  30128. BABYLON.VertexBuffer = VertexBuffer;
  30129. })(BABYLON || (BABYLON = {}));
  30130. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30131. var BABYLON;
  30132. (function (BABYLON) {
  30133. /**
  30134. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30135. */
  30136. var DummyInternalTextureTracker = /** @class */ (function () {
  30137. function DummyInternalTextureTracker() {
  30138. /**
  30139. * Gets or set the previous tracker in the list
  30140. */
  30141. this.previous = null;
  30142. /**
  30143. * Gets or set the next tracker in the list
  30144. */
  30145. this.next = null;
  30146. }
  30147. return DummyInternalTextureTracker;
  30148. }());
  30149. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30150. })(BABYLON || (BABYLON = {}));
  30151. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30152. var BABYLON;
  30153. (function (BABYLON) {
  30154. /**
  30155. * Class used to store data associated with WebGL texture data for the engine
  30156. * This class should not be used directly
  30157. */
  30158. var InternalTexture = /** @class */ (function () {
  30159. /**
  30160. * Creates a new InternalTexture
  30161. * @param engine defines the engine to use
  30162. * @param dataSource defines the type of data that will be used
  30163. */
  30164. function InternalTexture(engine, dataSource) {
  30165. /**
  30166. * Observable called when the texture is loaded
  30167. */
  30168. this.onLoadedObservable = new BABYLON.Observable();
  30169. /**
  30170. * Gets or set the previous tracker in the list
  30171. */
  30172. this.previous = null;
  30173. /**
  30174. * Gets or set the next tracker in the list
  30175. */
  30176. this.next = null;
  30177. // Private
  30178. /** @hidden */
  30179. this._initialSlot = -1;
  30180. /** @hidden */
  30181. this._designatedSlot = -1;
  30182. /** @hidden */
  30183. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30184. /** @hidden */
  30185. this._comparisonFunction = 0;
  30186. /** @hidden */
  30187. this._lodGenerationScale = 0;
  30188. /** @hidden */
  30189. this._lodGenerationOffset = 0;
  30190. /** @hidden */
  30191. this._isRGBD = false;
  30192. /** @hidden */
  30193. this._references = 1;
  30194. this._engine = engine;
  30195. this._dataSource = dataSource;
  30196. this._webGLTexture = engine._createTexture();
  30197. }
  30198. /**
  30199. * Gets the Engine the texture belongs to.
  30200. * @returns The babylon engine
  30201. */
  30202. InternalTexture.prototype.getEngine = function () {
  30203. return this._engine;
  30204. };
  30205. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30206. /**
  30207. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30208. */
  30209. get: function () {
  30210. return this._dataSource;
  30211. },
  30212. enumerable: true,
  30213. configurable: true
  30214. });
  30215. /**
  30216. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30217. */
  30218. InternalTexture.prototype.incrementReferences = function () {
  30219. this._references++;
  30220. };
  30221. /**
  30222. * Change the size of the texture (not the size of the content)
  30223. * @param width defines the new width
  30224. * @param height defines the new height
  30225. * @param depth defines the new depth (1 by default)
  30226. */
  30227. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30228. if (depth === void 0) { depth = 1; }
  30229. this.width = width;
  30230. this.height = height;
  30231. this.depth = depth;
  30232. this.baseWidth = width;
  30233. this.baseHeight = height;
  30234. this.baseDepth = depth;
  30235. this._size = width * height * depth;
  30236. };
  30237. /** @hidden */
  30238. InternalTexture.prototype._rebuild = function () {
  30239. var _this = this;
  30240. var proxy;
  30241. this.isReady = false;
  30242. this._cachedCoordinatesMode = null;
  30243. this._cachedWrapU = null;
  30244. this._cachedWrapV = null;
  30245. this._cachedAnisotropicFilteringLevel = null;
  30246. switch (this._dataSource) {
  30247. case InternalTexture.DATASOURCE_TEMP:
  30248. return;
  30249. case InternalTexture.DATASOURCE_URL:
  30250. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30251. _this.isReady = true;
  30252. }, null, this._buffer, undefined, this.format);
  30253. proxy._swapAndDie(this);
  30254. return;
  30255. case InternalTexture.DATASOURCE_RAW:
  30256. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30257. proxy._swapAndDie(this);
  30258. this.isReady = true;
  30259. return;
  30260. case InternalTexture.DATASOURCE_RAW3D:
  30261. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30262. proxy._swapAndDie(this);
  30263. this.isReady = true;
  30264. return;
  30265. case InternalTexture.DATASOURCE_DYNAMIC:
  30266. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30267. proxy._swapAndDie(this);
  30268. // The engine will make sure to update content so no need to flag it as isReady = true
  30269. return;
  30270. case InternalTexture.DATASOURCE_RENDERTARGET:
  30271. var options = new BABYLON.RenderTargetCreationOptions();
  30272. options.generateDepthBuffer = this._generateDepthBuffer;
  30273. options.generateMipMaps = this.generateMipMaps;
  30274. options.generateStencilBuffer = this._generateStencilBuffer;
  30275. options.samplingMode = this.samplingMode;
  30276. options.type = this.type;
  30277. if (this.isCube) {
  30278. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30279. }
  30280. else {
  30281. var size = {
  30282. width: this.width,
  30283. height: this.height
  30284. };
  30285. proxy = this._engine.createRenderTargetTexture(size, options);
  30286. }
  30287. proxy._swapAndDie(this);
  30288. this.isReady = true;
  30289. return;
  30290. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30291. var depthTextureOptions = {
  30292. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30293. comparisonFunction: this._comparisonFunction,
  30294. generateStencil: this._generateStencilBuffer,
  30295. isCube: this.isCube
  30296. };
  30297. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30298. proxy._swapAndDie(this);
  30299. this.isReady = true;
  30300. return;
  30301. case InternalTexture.DATASOURCE_CUBE:
  30302. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30303. _this.isReady = true;
  30304. }, null, this.format, this._extension);
  30305. proxy._swapAndDie(this);
  30306. return;
  30307. case InternalTexture.DATASOURCE_CUBERAW:
  30308. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30309. proxy._swapAndDie(this);
  30310. this.isReady = true;
  30311. return;
  30312. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30313. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30314. if (proxy) {
  30315. proxy._swapAndDie(_this);
  30316. }
  30317. _this.isReady = true;
  30318. }, null, this.format, this._extension);
  30319. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30320. return;
  30321. }
  30322. };
  30323. InternalTexture.prototype._swapAndDie = function (target) {
  30324. target._webGLTexture = this._webGLTexture;
  30325. if (this._framebuffer) {
  30326. target._framebuffer = this._framebuffer;
  30327. }
  30328. if (this._depthStencilBuffer) {
  30329. target._depthStencilBuffer = this._depthStencilBuffer;
  30330. }
  30331. if (this._lodTextureHigh) {
  30332. if (target._lodTextureHigh) {
  30333. target._lodTextureHigh.dispose();
  30334. }
  30335. target._lodTextureHigh = this._lodTextureHigh;
  30336. }
  30337. if (this._lodTextureMid) {
  30338. if (target._lodTextureMid) {
  30339. target._lodTextureMid.dispose();
  30340. }
  30341. target._lodTextureMid = this._lodTextureMid;
  30342. }
  30343. if (this._lodTextureLow) {
  30344. if (target._lodTextureLow) {
  30345. target._lodTextureLow.dispose();
  30346. }
  30347. target._lodTextureLow = this._lodTextureLow;
  30348. }
  30349. var cache = this._engine.getLoadedTexturesCache();
  30350. var index = cache.indexOf(this);
  30351. if (index !== -1) {
  30352. cache.splice(index, 1);
  30353. }
  30354. };
  30355. /**
  30356. * Dispose the current allocated resources
  30357. */
  30358. InternalTexture.prototype.dispose = function () {
  30359. if (!this._webGLTexture) {
  30360. return;
  30361. }
  30362. this._references--;
  30363. if (this._references === 0) {
  30364. this._engine._releaseTexture(this);
  30365. this._webGLTexture = null;
  30366. this.previous = null;
  30367. this.next = null;
  30368. }
  30369. };
  30370. /**
  30371. * The source of the texture data is unknown
  30372. */
  30373. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30374. /**
  30375. * Texture data comes from an URL
  30376. */
  30377. InternalTexture.DATASOURCE_URL = 1;
  30378. /**
  30379. * Texture data is only used for temporary storage
  30380. */
  30381. InternalTexture.DATASOURCE_TEMP = 2;
  30382. /**
  30383. * Texture data comes from raw data (ArrayBuffer)
  30384. */
  30385. InternalTexture.DATASOURCE_RAW = 3;
  30386. /**
  30387. * Texture content is dynamic (video or dynamic texture)
  30388. */
  30389. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30390. /**
  30391. * Texture content is generated by rendering to it
  30392. */
  30393. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30394. /**
  30395. * Texture content is part of a multi render target process
  30396. */
  30397. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30398. /**
  30399. * Texture data comes from a cube data file
  30400. */
  30401. InternalTexture.DATASOURCE_CUBE = 7;
  30402. /**
  30403. * Texture data comes from a raw cube data
  30404. */
  30405. InternalTexture.DATASOURCE_CUBERAW = 8;
  30406. /**
  30407. * Texture data come from a prefiltered cube data file
  30408. */
  30409. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30410. /**
  30411. * Texture content is raw 3D data
  30412. */
  30413. InternalTexture.DATASOURCE_RAW3D = 10;
  30414. /**
  30415. * Texture content is a depth texture
  30416. */
  30417. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30418. return InternalTexture;
  30419. }());
  30420. BABYLON.InternalTexture = InternalTexture;
  30421. })(BABYLON || (BABYLON = {}));
  30422. //# sourceMappingURL=babylon.internalTexture.js.map
  30423. var BABYLON;
  30424. (function (BABYLON) {
  30425. var BaseTexture = /** @class */ (function () {
  30426. function BaseTexture(scene) {
  30427. this._hasAlpha = false;
  30428. this.getAlphaFromRGB = false;
  30429. this.level = 1;
  30430. this.coordinatesIndex = 0;
  30431. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30432. /**
  30433. * | Value | Type | Description |
  30434. * | ----- | ------------------ | ----------- |
  30435. * | 0 | CLAMP_ADDRESSMODE | |
  30436. * | 1 | WRAP_ADDRESSMODE | |
  30437. * | 2 | MIRROR_ADDRESSMODE | |
  30438. */
  30439. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30440. /**
  30441. * | Value | Type | Description |
  30442. * | ----- | ------------------ | ----------- |
  30443. * | 0 | CLAMP_ADDRESSMODE | |
  30444. * | 1 | WRAP_ADDRESSMODE | |
  30445. * | 2 | MIRROR_ADDRESSMODE | |
  30446. */
  30447. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30448. /**
  30449. * | Value | Type | Description |
  30450. * | ----- | ------------------ | ----------- |
  30451. * | 0 | CLAMP_ADDRESSMODE | |
  30452. * | 1 | WRAP_ADDRESSMODE | |
  30453. * | 2 | MIRROR_ADDRESSMODE | |
  30454. */
  30455. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30456. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30457. this.isCube = false;
  30458. this.is3D = false;
  30459. this.gammaSpace = true;
  30460. this.invertZ = false;
  30461. this.lodLevelInAlpha = false;
  30462. this.isRenderTarget = false;
  30463. this.animations = new Array();
  30464. /**
  30465. * An event triggered when the texture is disposed.
  30466. */
  30467. this.onDisposeObservable = new BABYLON.Observable();
  30468. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30469. this._cachedSize = BABYLON.Size.Zero();
  30470. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30471. if (this._scene) {
  30472. this._scene.textures.push(this);
  30473. }
  30474. this._uid = null;
  30475. }
  30476. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30477. get: function () {
  30478. return this._hasAlpha;
  30479. },
  30480. set: function (value) {
  30481. if (this._hasAlpha === value) {
  30482. return;
  30483. }
  30484. this._hasAlpha = value;
  30485. if (this._scene) {
  30486. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30487. }
  30488. },
  30489. enumerable: true,
  30490. configurable: true
  30491. });
  30492. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30493. get: function () {
  30494. return this._coordinatesMode;
  30495. },
  30496. /**
  30497. * How a texture is mapped.
  30498. *
  30499. * | Value | Type | Description |
  30500. * | ----- | ----------------------------------- | ----------- |
  30501. * | 0 | EXPLICIT_MODE | |
  30502. * | 1 | SPHERICAL_MODE | |
  30503. * | 2 | PLANAR_MODE | |
  30504. * | 3 | CUBIC_MODE | |
  30505. * | 4 | PROJECTION_MODE | |
  30506. * | 5 | SKYBOX_MODE | |
  30507. * | 6 | INVCUBIC_MODE | |
  30508. * | 7 | EQUIRECTANGULAR_MODE | |
  30509. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30510. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30511. */
  30512. set: function (value) {
  30513. if (this._coordinatesMode === value) {
  30514. return;
  30515. }
  30516. this._coordinatesMode = value;
  30517. if (this._scene) {
  30518. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30519. }
  30520. },
  30521. enumerable: true,
  30522. configurable: true
  30523. });
  30524. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30525. /**
  30526. * Gets whether or not the texture contains RGBD data.
  30527. */
  30528. get: function () {
  30529. return this._texture != null && this._texture._isRGBD;
  30530. },
  30531. enumerable: true,
  30532. configurable: true
  30533. });
  30534. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30535. get: function () {
  30536. if (this._texture)
  30537. return this._texture._lodGenerationOffset;
  30538. return 0.0;
  30539. },
  30540. set: function (value) {
  30541. if (this._texture)
  30542. this._texture._lodGenerationOffset = value;
  30543. },
  30544. enumerable: true,
  30545. configurable: true
  30546. });
  30547. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30548. get: function () {
  30549. if (this._texture)
  30550. return this._texture._lodGenerationScale;
  30551. return 0.0;
  30552. },
  30553. set: function (value) {
  30554. if (this._texture)
  30555. this._texture._lodGenerationScale = value;
  30556. },
  30557. enumerable: true,
  30558. configurable: true
  30559. });
  30560. Object.defineProperty(BaseTexture.prototype, "uid", {
  30561. get: function () {
  30562. if (!this._uid) {
  30563. this._uid = BABYLON.Tools.RandomId();
  30564. }
  30565. return this._uid;
  30566. },
  30567. enumerable: true,
  30568. configurable: true
  30569. });
  30570. BaseTexture.prototype.toString = function () {
  30571. return this.name;
  30572. };
  30573. BaseTexture.prototype.getClassName = function () {
  30574. return "BaseTexture";
  30575. };
  30576. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30577. set: function (callback) {
  30578. if (this._onDisposeObserver) {
  30579. this.onDisposeObservable.remove(this._onDisposeObserver);
  30580. }
  30581. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30582. },
  30583. enumerable: true,
  30584. configurable: true
  30585. });
  30586. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30587. get: function () {
  30588. return true;
  30589. },
  30590. enumerable: true,
  30591. configurable: true
  30592. });
  30593. BaseTexture.prototype.getScene = function () {
  30594. return this._scene;
  30595. };
  30596. BaseTexture.prototype.getTextureMatrix = function () {
  30597. return BABYLON.Matrix.IdentityReadOnly;
  30598. };
  30599. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30600. return BABYLON.Matrix.IdentityReadOnly;
  30601. };
  30602. BaseTexture.prototype.getInternalTexture = function () {
  30603. return this._texture;
  30604. };
  30605. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30606. return !this.isBlocking || this.isReady();
  30607. };
  30608. BaseTexture.prototype.isReady = function () {
  30609. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30610. this.delayLoad();
  30611. return false;
  30612. }
  30613. if (this._texture) {
  30614. return this._texture.isReady;
  30615. }
  30616. return false;
  30617. };
  30618. BaseTexture.prototype.getSize = function () {
  30619. if (this._texture) {
  30620. if (this._texture.width) {
  30621. this._cachedSize.width = this._texture.width;
  30622. this._cachedSize.height = this._texture.height;
  30623. return this._cachedSize;
  30624. }
  30625. if (this._texture._size) {
  30626. this._cachedSize.width = this._texture._size;
  30627. this._cachedSize.height = this._texture._size;
  30628. return this._cachedSize;
  30629. }
  30630. }
  30631. return this._cachedSize;
  30632. };
  30633. BaseTexture.prototype.getBaseSize = function () {
  30634. if (!this.isReady() || !this._texture)
  30635. return BABYLON.Size.Zero();
  30636. if (this._texture._size) {
  30637. return new BABYLON.Size(this._texture._size, this._texture._size);
  30638. }
  30639. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30640. };
  30641. BaseTexture.prototype.scale = function (ratio) {
  30642. };
  30643. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30644. get: function () {
  30645. return false;
  30646. },
  30647. enumerable: true,
  30648. configurable: true
  30649. });
  30650. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30651. if (!this._scene) {
  30652. return null;
  30653. }
  30654. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30655. for (var index = 0; index < texturesCache.length; index++) {
  30656. var texturesCacheEntry = texturesCache[index];
  30657. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30658. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30659. texturesCacheEntry.incrementReferences();
  30660. return texturesCacheEntry;
  30661. }
  30662. }
  30663. }
  30664. return null;
  30665. };
  30666. BaseTexture.prototype._rebuild = function () {
  30667. };
  30668. BaseTexture.prototype.delayLoad = function () {
  30669. };
  30670. BaseTexture.prototype.clone = function () {
  30671. return null;
  30672. };
  30673. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30674. get: function () {
  30675. if (!this._texture) {
  30676. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30677. }
  30678. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30679. },
  30680. enumerable: true,
  30681. configurable: true
  30682. });
  30683. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30684. get: function () {
  30685. if (!this._texture) {
  30686. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30687. }
  30688. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30689. },
  30690. enumerable: true,
  30691. configurable: true
  30692. });
  30693. /**
  30694. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30695. * This will returns an RGBA array buffer containing either in values (0-255) or
  30696. * float values (0-1) depending of the underlying buffer type.
  30697. * @param faceIndex The face of the texture to read (in case of cube texture)
  30698. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30699. * @returns The Array buffer containing the pixels data.
  30700. */
  30701. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30702. if (faceIndex === void 0) { faceIndex = 0; }
  30703. if (level === void 0) { level = 0; }
  30704. if (!this._texture) {
  30705. return null;
  30706. }
  30707. var size = this.getSize();
  30708. var width = size.width;
  30709. var height = size.height;
  30710. var scene = this.getScene();
  30711. if (!scene) {
  30712. return null;
  30713. }
  30714. var engine = scene.getEngine();
  30715. if (level != 0) {
  30716. width = width / Math.pow(2, level);
  30717. height = height / Math.pow(2, level);
  30718. width = Math.round(width);
  30719. height = Math.round(height);
  30720. }
  30721. if (this._texture.isCube) {
  30722. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30723. }
  30724. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30725. };
  30726. BaseTexture.prototype.releaseInternalTexture = function () {
  30727. if (this._texture) {
  30728. this._texture.dispose();
  30729. this._texture = null;
  30730. }
  30731. };
  30732. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30733. get: function () {
  30734. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30735. return null;
  30736. }
  30737. if (!this._texture._sphericalPolynomial) {
  30738. this._texture._sphericalPolynomial =
  30739. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30740. }
  30741. return this._texture._sphericalPolynomial;
  30742. },
  30743. set: function (value) {
  30744. if (this._texture) {
  30745. this._texture._sphericalPolynomial = value;
  30746. }
  30747. },
  30748. enumerable: true,
  30749. configurable: true
  30750. });
  30751. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30752. get: function () {
  30753. if (this._texture) {
  30754. return this._texture._lodTextureHigh;
  30755. }
  30756. return null;
  30757. },
  30758. enumerable: true,
  30759. configurable: true
  30760. });
  30761. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30762. get: function () {
  30763. if (this._texture) {
  30764. return this._texture._lodTextureMid;
  30765. }
  30766. return null;
  30767. },
  30768. enumerable: true,
  30769. configurable: true
  30770. });
  30771. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30772. get: function () {
  30773. if (this._texture) {
  30774. return this._texture._lodTextureLow;
  30775. }
  30776. return null;
  30777. },
  30778. enumerable: true,
  30779. configurable: true
  30780. });
  30781. BaseTexture.prototype.dispose = function () {
  30782. if (!this._scene) {
  30783. return;
  30784. }
  30785. // Animations
  30786. this._scene.stopAnimation(this);
  30787. // Remove from scene
  30788. this._scene._removePendingData(this);
  30789. var index = this._scene.textures.indexOf(this);
  30790. if (index >= 0) {
  30791. this._scene.textures.splice(index, 1);
  30792. }
  30793. if (this._texture === undefined) {
  30794. return;
  30795. }
  30796. // Release
  30797. this.releaseInternalTexture();
  30798. // Callback
  30799. this.onDisposeObservable.notifyObservers(this);
  30800. this.onDisposeObservable.clear();
  30801. };
  30802. BaseTexture.prototype.serialize = function () {
  30803. if (!this.name) {
  30804. return null;
  30805. }
  30806. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30807. // Animations
  30808. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30809. return serializationObject;
  30810. };
  30811. BaseTexture.WhenAllReady = function (textures, callback) {
  30812. var numRemaining = textures.length;
  30813. if (numRemaining === 0) {
  30814. callback();
  30815. return;
  30816. }
  30817. var _loop_1 = function () {
  30818. texture = textures[i];
  30819. if (texture.isReady()) {
  30820. if (--numRemaining === 0) {
  30821. callback();
  30822. }
  30823. }
  30824. else {
  30825. onLoadObservable = texture.onLoadObservable;
  30826. var onLoadCallback_1 = function () {
  30827. onLoadObservable.removeCallback(onLoadCallback_1);
  30828. if (--numRemaining === 0) {
  30829. callback();
  30830. }
  30831. };
  30832. onLoadObservable.add(onLoadCallback_1);
  30833. }
  30834. };
  30835. var texture, onLoadObservable;
  30836. for (var i = 0; i < textures.length; i++) {
  30837. _loop_1();
  30838. }
  30839. };
  30840. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30841. __decorate([
  30842. BABYLON.serialize()
  30843. ], BaseTexture.prototype, "name", void 0);
  30844. __decorate([
  30845. BABYLON.serialize("hasAlpha")
  30846. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30847. __decorate([
  30848. BABYLON.serialize()
  30849. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30850. __decorate([
  30851. BABYLON.serialize()
  30852. ], BaseTexture.prototype, "level", void 0);
  30853. __decorate([
  30854. BABYLON.serialize()
  30855. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30856. __decorate([
  30857. BABYLON.serialize("coordinatesMode")
  30858. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30859. __decorate([
  30860. BABYLON.serialize()
  30861. ], BaseTexture.prototype, "wrapU", void 0);
  30862. __decorate([
  30863. BABYLON.serialize()
  30864. ], BaseTexture.prototype, "wrapV", void 0);
  30865. __decorate([
  30866. BABYLON.serialize()
  30867. ], BaseTexture.prototype, "wrapR", void 0);
  30868. __decorate([
  30869. BABYLON.serialize()
  30870. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30871. __decorate([
  30872. BABYLON.serialize()
  30873. ], BaseTexture.prototype, "isCube", void 0);
  30874. __decorate([
  30875. BABYLON.serialize()
  30876. ], BaseTexture.prototype, "is3D", void 0);
  30877. __decorate([
  30878. BABYLON.serialize()
  30879. ], BaseTexture.prototype, "gammaSpace", void 0);
  30880. __decorate([
  30881. BABYLON.serialize()
  30882. ], BaseTexture.prototype, "invertZ", void 0);
  30883. __decorate([
  30884. BABYLON.serialize()
  30885. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30886. __decorate([
  30887. BABYLON.serialize()
  30888. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30889. __decorate([
  30890. BABYLON.serialize()
  30891. ], BaseTexture.prototype, "lodGenerationScale", null);
  30892. __decorate([
  30893. BABYLON.serialize()
  30894. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30895. return BaseTexture;
  30896. }());
  30897. BABYLON.BaseTexture = BaseTexture;
  30898. })(BABYLON || (BABYLON = {}));
  30899. //# sourceMappingURL=babylon.baseTexture.js.map
  30900. var BABYLON;
  30901. (function (BABYLON) {
  30902. var Texture = /** @class */ (function (_super) {
  30903. __extends(Texture, _super);
  30904. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30905. if (noMipmap === void 0) { noMipmap = false; }
  30906. if (invertY === void 0) { invertY = true; }
  30907. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30908. if (onLoad === void 0) { onLoad = null; }
  30909. if (onError === void 0) { onError = null; }
  30910. if (buffer === void 0) { buffer = null; }
  30911. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30912. var _this = _super.call(this, scene) || this;
  30913. _this.uOffset = 0;
  30914. _this.vOffset = 0;
  30915. _this.uScale = 1.0;
  30916. _this.vScale = 1.0;
  30917. _this.uAng = 0;
  30918. _this.vAng = 0;
  30919. _this.wAng = 0;
  30920. /**
  30921. * Defines the center of rotation (U)
  30922. */
  30923. _this.uRotationCenter = 0.5;
  30924. /**
  30925. * Defines the center of rotation (V)
  30926. */
  30927. _this.vRotationCenter = 0.5;
  30928. /**
  30929. * Defines the center of rotation (W)
  30930. */
  30931. _this.wRotationCenter = 0.5;
  30932. _this._isBlocking = true;
  30933. _this.name = url || "";
  30934. _this.url = url;
  30935. _this._noMipmap = noMipmap;
  30936. _this._invertY = invertY;
  30937. _this._samplingMode = samplingMode;
  30938. _this._buffer = buffer;
  30939. _this._deleteBuffer = deleteBuffer;
  30940. if (format) {
  30941. _this._format = format;
  30942. }
  30943. scene = _this.getScene();
  30944. if (!scene) {
  30945. return _this;
  30946. }
  30947. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30948. var load = function () {
  30949. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30950. _this.onLoadObservable.notifyObservers(_this);
  30951. }
  30952. if (onLoad) {
  30953. onLoad();
  30954. }
  30955. if (!_this.isBlocking && scene) {
  30956. scene.resetCachedMaterial();
  30957. }
  30958. };
  30959. if (!_this.url) {
  30960. _this._delayedOnLoad = load;
  30961. _this._delayedOnError = onError;
  30962. return _this;
  30963. }
  30964. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30965. if (!_this._texture) {
  30966. if (!scene.useDelayedTextureLoading) {
  30967. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30968. if (deleteBuffer) {
  30969. delete _this._buffer;
  30970. }
  30971. }
  30972. else {
  30973. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30974. _this._delayedOnLoad = load;
  30975. _this._delayedOnError = onError;
  30976. }
  30977. }
  30978. else {
  30979. if (_this._texture.isReady) {
  30980. BABYLON.Tools.SetImmediate(function () { return load(); });
  30981. }
  30982. else {
  30983. _this._texture.onLoadedObservable.add(load);
  30984. }
  30985. }
  30986. return _this;
  30987. }
  30988. Object.defineProperty(Texture.prototype, "noMipmap", {
  30989. get: function () {
  30990. return this._noMipmap;
  30991. },
  30992. enumerable: true,
  30993. configurable: true
  30994. });
  30995. Object.defineProperty(Texture.prototype, "isBlocking", {
  30996. get: function () {
  30997. return this._isBlocking;
  30998. },
  30999. set: function (value) {
  31000. this._isBlocking = value;
  31001. },
  31002. enumerable: true,
  31003. configurable: true
  31004. });
  31005. Object.defineProperty(Texture.prototype, "samplingMode", {
  31006. get: function () {
  31007. return this._samplingMode;
  31008. },
  31009. enumerable: true,
  31010. configurable: true
  31011. });
  31012. /**
  31013. * Update the url (and optional buffer) of this texture if url was null during construction.
  31014. * @param url the url of the texture
  31015. * @param buffer the buffer of the texture (defaults to null)
  31016. */
  31017. Texture.prototype.updateURL = function (url, buffer) {
  31018. if (buffer === void 0) { buffer = null; }
  31019. if (this.url) {
  31020. throw new Error("URL is already set");
  31021. }
  31022. this.url = url;
  31023. this._buffer = buffer;
  31024. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31025. this.delayLoad();
  31026. };
  31027. Texture.prototype.delayLoad = function () {
  31028. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31029. return;
  31030. }
  31031. var scene = this.getScene();
  31032. if (!scene) {
  31033. return;
  31034. }
  31035. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31036. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31037. if (!this._texture) {
  31038. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31039. if (this._deleteBuffer) {
  31040. delete this._buffer;
  31041. }
  31042. }
  31043. else {
  31044. if (this._delayedOnLoad) {
  31045. if (this._texture.isReady) {
  31046. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31047. }
  31048. else {
  31049. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31050. }
  31051. }
  31052. }
  31053. this._delayedOnLoad = null;
  31054. this._delayedOnError = null;
  31055. };
  31056. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31057. if (!this._texture) {
  31058. return;
  31059. }
  31060. var scene = this.getScene();
  31061. if (!scene) {
  31062. return;
  31063. }
  31064. this._samplingMode = samplingMode;
  31065. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31066. };
  31067. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31068. x *= this.uScale;
  31069. y *= this.vScale;
  31070. x -= this.uRotationCenter * this.uScale;
  31071. y -= this.vRotationCenter * this.vScale;
  31072. z -= this.wRotationCenter;
  31073. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31074. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31075. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31076. t.z += this.wRotationCenter;
  31077. };
  31078. Texture.prototype.getTextureMatrix = function () {
  31079. var _this = this;
  31080. if (this.uOffset === this._cachedUOffset &&
  31081. this.vOffset === this._cachedVOffset &&
  31082. this.uScale === this._cachedUScale &&
  31083. this.vScale === this._cachedVScale &&
  31084. this.uAng === this._cachedUAng &&
  31085. this.vAng === this._cachedVAng &&
  31086. this.wAng === this._cachedWAng) {
  31087. return this._cachedTextureMatrix;
  31088. }
  31089. this._cachedUOffset = this.uOffset;
  31090. this._cachedVOffset = this.vOffset;
  31091. this._cachedUScale = this.uScale;
  31092. this._cachedVScale = this.vScale;
  31093. this._cachedUAng = this.uAng;
  31094. this._cachedVAng = this.vAng;
  31095. this._cachedWAng = this.wAng;
  31096. if (!this._cachedTextureMatrix) {
  31097. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31098. this._rowGenerationMatrix = new BABYLON.Matrix();
  31099. this._t0 = BABYLON.Vector3.Zero();
  31100. this._t1 = BABYLON.Vector3.Zero();
  31101. this._t2 = BABYLON.Vector3.Zero();
  31102. }
  31103. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31104. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31105. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31106. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31107. this._t1.subtractInPlace(this._t0);
  31108. this._t2.subtractInPlace(this._t0);
  31109. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31110. this._cachedTextureMatrix.m[0] = this._t1.x;
  31111. this._cachedTextureMatrix.m[1] = this._t1.y;
  31112. this._cachedTextureMatrix.m[2] = this._t1.z;
  31113. this._cachedTextureMatrix.m[4] = this._t2.x;
  31114. this._cachedTextureMatrix.m[5] = this._t2.y;
  31115. this._cachedTextureMatrix.m[6] = this._t2.z;
  31116. this._cachedTextureMatrix.m[8] = this._t0.x;
  31117. this._cachedTextureMatrix.m[9] = this._t0.y;
  31118. this._cachedTextureMatrix.m[10] = this._t0.z;
  31119. var scene = this.getScene();
  31120. if (!scene) {
  31121. return this._cachedTextureMatrix;
  31122. }
  31123. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31124. return mat.hasTexture(_this);
  31125. });
  31126. return this._cachedTextureMatrix;
  31127. };
  31128. Texture.prototype.getReflectionTextureMatrix = function () {
  31129. var _this = this;
  31130. var scene = this.getScene();
  31131. if (!scene) {
  31132. return this._cachedTextureMatrix;
  31133. }
  31134. if (this.uOffset === this._cachedUOffset &&
  31135. this.vOffset === this._cachedVOffset &&
  31136. this.uScale === this._cachedUScale &&
  31137. this.vScale === this._cachedVScale &&
  31138. this.coordinatesMode === this._cachedCoordinatesMode) {
  31139. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31140. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31141. return this._cachedTextureMatrix;
  31142. }
  31143. }
  31144. else {
  31145. return this._cachedTextureMatrix;
  31146. }
  31147. }
  31148. if (!this._cachedTextureMatrix) {
  31149. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31150. }
  31151. if (!this._projectionModeMatrix) {
  31152. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31153. }
  31154. this._cachedUOffset = this.uOffset;
  31155. this._cachedVOffset = this.vOffset;
  31156. this._cachedUScale = this.uScale;
  31157. this._cachedVScale = this.vScale;
  31158. this._cachedCoordinatesMode = this.coordinatesMode;
  31159. switch (this.coordinatesMode) {
  31160. case Texture.PLANAR_MODE:
  31161. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31162. this._cachedTextureMatrix[0] = this.uScale;
  31163. this._cachedTextureMatrix[5] = this.vScale;
  31164. this._cachedTextureMatrix[12] = this.uOffset;
  31165. this._cachedTextureMatrix[13] = this.vOffset;
  31166. break;
  31167. case Texture.PROJECTION_MODE:
  31168. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31169. this._projectionModeMatrix.m[0] = 0.5;
  31170. this._projectionModeMatrix.m[5] = -0.5;
  31171. this._projectionModeMatrix.m[10] = 0.0;
  31172. this._projectionModeMatrix.m[12] = 0.5;
  31173. this._projectionModeMatrix.m[13] = 0.5;
  31174. this._projectionModeMatrix.m[14] = 1.0;
  31175. this._projectionModeMatrix.m[15] = 1.0;
  31176. var projectionMatrix = scene.getProjectionMatrix();
  31177. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31178. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31179. break;
  31180. default:
  31181. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31182. break;
  31183. }
  31184. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31185. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31186. });
  31187. return this._cachedTextureMatrix;
  31188. };
  31189. Texture.prototype.clone = function () {
  31190. var _this = this;
  31191. return BABYLON.SerializationHelper.Clone(function () {
  31192. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31193. }, this);
  31194. };
  31195. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31196. get: function () {
  31197. if (!this._onLoadObservable) {
  31198. this._onLoadObservable = new BABYLON.Observable();
  31199. }
  31200. return this._onLoadObservable;
  31201. },
  31202. enumerable: true,
  31203. configurable: true
  31204. });
  31205. Texture.prototype.serialize = function () {
  31206. var serializationObject = _super.prototype.serialize.call(this);
  31207. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31208. serializationObject.base64String = this._buffer;
  31209. serializationObject.name = serializationObject.name.replace("data:", "");
  31210. }
  31211. serializationObject.invertY = this._invertY;
  31212. serializationObject.samplingMode = this.samplingMode;
  31213. return serializationObject;
  31214. };
  31215. Texture.prototype.getClassName = function () {
  31216. return "Texture";
  31217. };
  31218. Texture.prototype.dispose = function () {
  31219. _super.prototype.dispose.call(this);
  31220. if (this._onLoadObservable) {
  31221. this._onLoadObservable.clear();
  31222. this._onLoadObservable = null;
  31223. }
  31224. this._delayedOnLoad = null;
  31225. this._delayedOnError = null;
  31226. };
  31227. // Statics
  31228. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31229. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31230. if (onLoad === void 0) { onLoad = null; }
  31231. if (onError === void 0) { onError = null; }
  31232. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31233. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31234. };
  31235. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31236. if (parsedTexture.customType) {
  31237. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31238. // Update Sampling Mode
  31239. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31240. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31241. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31242. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31243. }
  31244. }
  31245. return parsedCustomTexture;
  31246. }
  31247. if (parsedTexture.isCube) {
  31248. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31249. }
  31250. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31251. return null;
  31252. }
  31253. var texture = BABYLON.SerializationHelper.Parse(function () {
  31254. var generateMipMaps = true;
  31255. if (parsedTexture.noMipmap) {
  31256. generateMipMaps = false;
  31257. }
  31258. if (parsedTexture.mirrorPlane) {
  31259. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31260. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31261. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31262. return mirrorTexture;
  31263. }
  31264. else if (parsedTexture.isRenderTarget) {
  31265. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31266. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31267. return renderTargetTexture;
  31268. }
  31269. else {
  31270. var texture;
  31271. if (parsedTexture.base64String) {
  31272. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31273. }
  31274. else {
  31275. var url = rootUrl + parsedTexture.name;
  31276. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31277. url = parsedTexture.url;
  31278. }
  31279. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31280. }
  31281. return texture;
  31282. }
  31283. }, parsedTexture, scene);
  31284. // Update Sampling Mode
  31285. if (parsedTexture.samplingMode) {
  31286. var sampling = parsedTexture.samplingMode;
  31287. if (texture._samplingMode !== sampling) {
  31288. texture.updateSamplingMode(sampling);
  31289. }
  31290. }
  31291. // Animations
  31292. if (parsedTexture.animations) {
  31293. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31294. var parsedAnimation = parsedTexture.animations[animationIndex];
  31295. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31296. }
  31297. }
  31298. return texture;
  31299. };
  31300. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31301. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31302. if (noMipmap === void 0) { noMipmap = false; }
  31303. if (invertY === void 0) { invertY = true; }
  31304. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31305. if (onLoad === void 0) { onLoad = null; }
  31306. if (onError === void 0) { onError = null; }
  31307. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31308. if (name.substr(0, 5) !== "data:") {
  31309. name = "data:" + name;
  31310. }
  31311. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31312. };
  31313. // Constants
  31314. Texture.NEAREST_SAMPLINGMODE = 1;
  31315. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31316. Texture.BILINEAR_SAMPLINGMODE = 2;
  31317. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31318. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31319. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31320. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31321. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31322. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31323. Texture.NEAREST_LINEAR = 7;
  31324. Texture.NEAREST_NEAREST = 8;
  31325. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31326. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31327. Texture.LINEAR_LINEAR = 11;
  31328. Texture.LINEAR_NEAREST = 12;
  31329. Texture.EXPLICIT_MODE = 0;
  31330. Texture.SPHERICAL_MODE = 1;
  31331. Texture.PLANAR_MODE = 2;
  31332. Texture.CUBIC_MODE = 3;
  31333. Texture.PROJECTION_MODE = 4;
  31334. Texture.SKYBOX_MODE = 5;
  31335. Texture.INVCUBIC_MODE = 6;
  31336. Texture.EQUIRECTANGULAR_MODE = 7;
  31337. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31338. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31339. Texture.CLAMP_ADDRESSMODE = 0;
  31340. Texture.WRAP_ADDRESSMODE = 1;
  31341. Texture.MIRROR_ADDRESSMODE = 2;
  31342. /**
  31343. * 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
  31344. */
  31345. Texture.UseSerializedUrlIfAny = false;
  31346. __decorate([
  31347. BABYLON.serialize()
  31348. ], Texture.prototype, "url", void 0);
  31349. __decorate([
  31350. BABYLON.serialize()
  31351. ], Texture.prototype, "uOffset", void 0);
  31352. __decorate([
  31353. BABYLON.serialize()
  31354. ], Texture.prototype, "vOffset", void 0);
  31355. __decorate([
  31356. BABYLON.serialize()
  31357. ], Texture.prototype, "uScale", void 0);
  31358. __decorate([
  31359. BABYLON.serialize()
  31360. ], Texture.prototype, "vScale", void 0);
  31361. __decorate([
  31362. BABYLON.serialize()
  31363. ], Texture.prototype, "uAng", void 0);
  31364. __decorate([
  31365. BABYLON.serialize()
  31366. ], Texture.prototype, "vAng", void 0);
  31367. __decorate([
  31368. BABYLON.serialize()
  31369. ], Texture.prototype, "wAng", void 0);
  31370. __decorate([
  31371. BABYLON.serialize()
  31372. ], Texture.prototype, "uRotationCenter", void 0);
  31373. __decorate([
  31374. BABYLON.serialize()
  31375. ], Texture.prototype, "vRotationCenter", void 0);
  31376. __decorate([
  31377. BABYLON.serialize()
  31378. ], Texture.prototype, "wRotationCenter", void 0);
  31379. __decorate([
  31380. BABYLON.serialize()
  31381. ], Texture.prototype, "isBlocking", null);
  31382. return Texture;
  31383. }(BABYLON.BaseTexture));
  31384. BABYLON.Texture = Texture;
  31385. })(BABYLON || (BABYLON = {}));
  31386. //# sourceMappingURL=babylon.texture.js.map
  31387. var BABYLON;
  31388. (function (BABYLON) {
  31389. /**
  31390. * @hidden
  31391. **/
  31392. var _InstancesBatch = /** @class */ (function () {
  31393. function _InstancesBatch() {
  31394. this.mustReturn = false;
  31395. this.visibleInstances = new Array();
  31396. this.renderSelf = new Array();
  31397. }
  31398. return _InstancesBatch;
  31399. }());
  31400. BABYLON._InstancesBatch = _InstancesBatch;
  31401. var Mesh = /** @class */ (function (_super) {
  31402. __extends(Mesh, _super);
  31403. /**
  31404. * @constructor
  31405. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31406. * @param {Scene} scene The scene to add this mesh to.
  31407. * @param {Node} parent The parent of this mesh, if it has one
  31408. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31409. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31410. * When false, achieved by calling a clone(), also passing False.
  31411. * This will make creation of children, recursive.
  31412. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31413. */
  31414. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31415. if (scene === void 0) { scene = null; }
  31416. if (parent === void 0) { parent = null; }
  31417. if (source === void 0) { source = null; }
  31418. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31419. var _this = _super.call(this, name, scene) || this;
  31420. // Events
  31421. /**
  31422. * An event triggered before rendering the mesh
  31423. */
  31424. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31425. /**
  31426. * An event triggered after rendering the mesh
  31427. */
  31428. _this.onAfterRenderObservable = new BABYLON.Observable();
  31429. /**
  31430. * An event triggered before drawing the mesh
  31431. */
  31432. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31433. // Members
  31434. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31435. _this.instances = new Array();
  31436. _this._LODLevels = new Array();
  31437. _this._visibleInstances = {};
  31438. _this._renderIdForInstances = new Array();
  31439. _this._batchCache = new _InstancesBatch();
  31440. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31441. // Use by builder only to know what orientation were the mesh build in.
  31442. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31443. _this.overrideMaterialSideOrientation = null;
  31444. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31445. // Will be used to save a source mesh reference, If any
  31446. _this._source = null;
  31447. scene = _this.getScene();
  31448. if (source) {
  31449. // Geometry
  31450. if (source._geometry) {
  31451. source._geometry.applyToMesh(_this);
  31452. }
  31453. // Deep copy
  31454. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31455. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31456. // Source mesh
  31457. _this._source = source;
  31458. // Metadata
  31459. if (source.metadata && source.metadata.clone) {
  31460. _this.metadata = source.metadata.clone();
  31461. }
  31462. else {
  31463. _this.metadata = source.metadata;
  31464. }
  31465. // Tags
  31466. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31467. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31468. }
  31469. // Parent
  31470. _this.parent = source.parent;
  31471. // Pivot
  31472. _this.setPivotMatrix(source.getPivotMatrix());
  31473. _this.id = name + "." + source.id;
  31474. // Material
  31475. _this.material = source.material;
  31476. var index;
  31477. if (!doNotCloneChildren) {
  31478. // Children
  31479. var directDescendants = source.getDescendants(true);
  31480. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31481. var child = directDescendants[index_1];
  31482. if (child.clone) {
  31483. child.clone(name + "." + child.name, _this);
  31484. }
  31485. }
  31486. }
  31487. // Physics clone
  31488. var physicsEngine = _this.getScene().getPhysicsEngine();
  31489. if (clonePhysicsImpostor && physicsEngine) {
  31490. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31491. if (impostor) {
  31492. _this.physicsImpostor = impostor.clone(_this);
  31493. }
  31494. }
  31495. // Particles
  31496. for (index = 0; index < scene.particleSystems.length; index++) {
  31497. var system = scene.particleSystems[index];
  31498. if (system.emitter === source) {
  31499. system.clone(system.name, _this);
  31500. }
  31501. }
  31502. _this.refreshBoundingInfo();
  31503. _this.computeWorldMatrix(true);
  31504. }
  31505. // Parent
  31506. if (parent !== null) {
  31507. _this.parent = parent;
  31508. }
  31509. return _this;
  31510. }
  31511. Object.defineProperty(Mesh, "FRONTSIDE", {
  31512. /**
  31513. * Mesh side orientation : usually the external or front surface
  31514. */
  31515. get: function () {
  31516. return Mesh._FRONTSIDE;
  31517. },
  31518. enumerable: true,
  31519. configurable: true
  31520. });
  31521. Object.defineProperty(Mesh, "BACKSIDE", {
  31522. /**
  31523. * Mesh side orientation : usually the internal or back surface
  31524. */
  31525. get: function () {
  31526. return Mesh._BACKSIDE;
  31527. },
  31528. enumerable: true,
  31529. configurable: true
  31530. });
  31531. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31532. /**
  31533. * Mesh side orientation : both internal and external or front and back surfaces
  31534. */
  31535. get: function () {
  31536. return Mesh._DOUBLESIDE;
  31537. },
  31538. enumerable: true,
  31539. configurable: true
  31540. });
  31541. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31542. /**
  31543. * Mesh side orientation : by default, `FRONTSIDE`
  31544. */
  31545. get: function () {
  31546. return Mesh._DEFAULTSIDE;
  31547. },
  31548. enumerable: true,
  31549. configurable: true
  31550. });
  31551. Object.defineProperty(Mesh, "NO_CAP", {
  31552. /**
  31553. * Mesh cap setting : no cap
  31554. */
  31555. get: function () {
  31556. return Mesh._NO_CAP;
  31557. },
  31558. enumerable: true,
  31559. configurable: true
  31560. });
  31561. Object.defineProperty(Mesh, "CAP_START", {
  31562. /**
  31563. * Mesh cap setting : one cap at the beginning of the mesh
  31564. */
  31565. get: function () {
  31566. return Mesh._CAP_START;
  31567. },
  31568. enumerable: true,
  31569. configurable: true
  31570. });
  31571. Object.defineProperty(Mesh, "CAP_END", {
  31572. /**
  31573. * Mesh cap setting : one cap at the end of the mesh
  31574. */
  31575. get: function () {
  31576. return Mesh._CAP_END;
  31577. },
  31578. enumerable: true,
  31579. configurable: true
  31580. });
  31581. Object.defineProperty(Mesh, "CAP_ALL", {
  31582. /**
  31583. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31584. */
  31585. get: function () {
  31586. return Mesh._CAP_ALL;
  31587. },
  31588. enumerable: true,
  31589. configurable: true
  31590. });
  31591. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31592. set: function (callback) {
  31593. if (this._onBeforeDrawObserver) {
  31594. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31595. }
  31596. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31597. },
  31598. enumerable: true,
  31599. configurable: true
  31600. });
  31601. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31602. get: function () {
  31603. return this._morphTargetManager;
  31604. },
  31605. set: function (value) {
  31606. if (this._morphTargetManager === value) {
  31607. return;
  31608. }
  31609. this._morphTargetManager = value;
  31610. this._syncGeometryWithMorphTargetManager();
  31611. },
  31612. enumerable: true,
  31613. configurable: true
  31614. });
  31615. Object.defineProperty(Mesh.prototype, "source", {
  31616. get: function () {
  31617. return this._source;
  31618. },
  31619. enumerable: true,
  31620. configurable: true
  31621. });
  31622. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31623. get: function () {
  31624. return this._unIndexed;
  31625. },
  31626. set: function (value) {
  31627. if (this._unIndexed !== value) {
  31628. this._unIndexed = value;
  31629. this._markSubMeshesAsAttributesDirty();
  31630. }
  31631. },
  31632. enumerable: true,
  31633. configurable: true
  31634. });
  31635. // Methods
  31636. /**
  31637. * Returns the string "Mesh".
  31638. */
  31639. Mesh.prototype.getClassName = function () {
  31640. return "Mesh";
  31641. };
  31642. /**
  31643. * Returns a string.
  31644. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31645. */
  31646. Mesh.prototype.toString = function (fullDetails) {
  31647. var ret = _super.prototype.toString.call(this, fullDetails);
  31648. ret += ", n vertices: " + this.getTotalVertices();
  31649. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31650. if (this.animations) {
  31651. for (var i = 0; i < this.animations.length; i++) {
  31652. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31653. }
  31654. }
  31655. if (fullDetails) {
  31656. if (this._geometry) {
  31657. var ib = this.getIndices();
  31658. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31659. if (vb && ib) {
  31660. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31661. }
  31662. }
  31663. else {
  31664. ret += ", flat shading: UNKNOWN";
  31665. }
  31666. }
  31667. return ret;
  31668. };
  31669. Mesh.prototype._unBindEffect = function () {
  31670. _super.prototype._unBindEffect.call(this);
  31671. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31672. var instance = _a[_i];
  31673. instance._unBindEffect();
  31674. }
  31675. };
  31676. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31677. /**
  31678. * True if the mesh has some Levels Of Details (LOD).
  31679. * Returns a boolean.
  31680. */
  31681. get: function () {
  31682. return this._LODLevels.length > 0;
  31683. },
  31684. enumerable: true,
  31685. configurable: true
  31686. });
  31687. /**
  31688. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31689. * @returns an array of {BABYLON.MeshLODLevel}
  31690. */
  31691. Mesh.prototype.getLODLevels = function () {
  31692. return this._LODLevels;
  31693. };
  31694. Mesh.prototype._sortLODLevels = function () {
  31695. this._LODLevels.sort(function (a, b) {
  31696. if (a.distance < b.distance) {
  31697. return 1;
  31698. }
  31699. if (a.distance > b.distance) {
  31700. return -1;
  31701. }
  31702. return 0;
  31703. });
  31704. };
  31705. /**
  31706. * Add a mesh as LOD level triggered at the given distance.
  31707. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31708. * @param distance The distance from the center of the object to show this level
  31709. * @param mesh The mesh to be added as LOD level (can be null)
  31710. * @return This mesh (for chaining)
  31711. */
  31712. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31713. if (mesh && mesh._masterMesh) {
  31714. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31715. return this;
  31716. }
  31717. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31718. this._LODLevels.push(level);
  31719. if (mesh) {
  31720. mesh._masterMesh = this;
  31721. }
  31722. this._sortLODLevels();
  31723. return this;
  31724. };
  31725. /**
  31726. * Returns the LOD level mesh at the passed distance or null if not found.
  31727. * It is related to the method `addLODLevel(distance, mesh)`.
  31728. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31729. * Returns an object Mesh or `null`.
  31730. */
  31731. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31732. for (var index = 0; index < this._LODLevels.length; index++) {
  31733. var level = this._LODLevels[index];
  31734. if (level.distance === distance) {
  31735. return level.mesh;
  31736. }
  31737. }
  31738. return null;
  31739. };
  31740. /**
  31741. * Remove a mesh from the LOD array
  31742. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31743. * @param {Mesh} mesh The mesh to be removed.
  31744. * @return {Mesh} This mesh (for chaining)
  31745. */
  31746. Mesh.prototype.removeLODLevel = function (mesh) {
  31747. for (var index = 0; index < this._LODLevels.length; index++) {
  31748. if (this._LODLevels[index].mesh === mesh) {
  31749. this._LODLevels.splice(index, 1);
  31750. if (mesh) {
  31751. mesh._masterMesh = null;
  31752. }
  31753. }
  31754. }
  31755. this._sortLODLevels();
  31756. return this;
  31757. };
  31758. /**
  31759. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31760. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31761. */
  31762. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31763. if (!this._LODLevels || this._LODLevels.length === 0) {
  31764. return this;
  31765. }
  31766. var bSphere;
  31767. if (boundingSphere) {
  31768. bSphere = boundingSphere;
  31769. }
  31770. else {
  31771. var boundingInfo = this.getBoundingInfo();
  31772. bSphere = boundingInfo.boundingSphere;
  31773. }
  31774. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31775. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31776. if (this.onLODLevelSelection) {
  31777. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31778. }
  31779. return this;
  31780. }
  31781. for (var index = 0; index < this._LODLevels.length; index++) {
  31782. var level = this._LODLevels[index];
  31783. if (level.distance < distanceToCamera) {
  31784. if (level.mesh) {
  31785. level.mesh._preActivate();
  31786. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31787. }
  31788. if (this.onLODLevelSelection) {
  31789. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31790. }
  31791. return level.mesh;
  31792. }
  31793. }
  31794. if (this.onLODLevelSelection) {
  31795. this.onLODLevelSelection(distanceToCamera, this, this);
  31796. }
  31797. return this;
  31798. };
  31799. Object.defineProperty(Mesh.prototype, "geometry", {
  31800. /**
  31801. * Returns the mesh internal Geometry object.
  31802. */
  31803. get: function () {
  31804. return this._geometry;
  31805. },
  31806. enumerable: true,
  31807. configurable: true
  31808. });
  31809. /**
  31810. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31811. */
  31812. Mesh.prototype.getTotalVertices = function () {
  31813. if (this._geometry === null || this._geometry === undefined) {
  31814. return 0;
  31815. }
  31816. return this._geometry.getTotalVertices();
  31817. };
  31818. /**
  31819. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31820. * 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.
  31821. * You can force the copy with forceCopy === true
  31822. * Returns null if the mesh has no geometry or no vertex buffer.
  31823. * Possible `kind` values :
  31824. * - BABYLON.VertexBuffer.PositionKind
  31825. * - BABYLON.VertexBuffer.UVKind
  31826. * - BABYLON.VertexBuffer.UV2Kind
  31827. * - BABYLON.VertexBuffer.UV3Kind
  31828. * - BABYLON.VertexBuffer.UV4Kind
  31829. * - BABYLON.VertexBuffer.UV5Kind
  31830. * - BABYLON.VertexBuffer.UV6Kind
  31831. * - BABYLON.VertexBuffer.ColorKind
  31832. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31833. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31834. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31835. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31836. */
  31837. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31838. if (!this._geometry) {
  31839. return null;
  31840. }
  31841. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31842. };
  31843. /**
  31844. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31845. * Returns `null` if the mesh has no geometry.
  31846. * Possible `kind` values :
  31847. * - BABYLON.VertexBuffer.PositionKind
  31848. * - BABYLON.VertexBuffer.UVKind
  31849. * - BABYLON.VertexBuffer.UV2Kind
  31850. * - BABYLON.VertexBuffer.UV3Kind
  31851. * - BABYLON.VertexBuffer.UV4Kind
  31852. * - BABYLON.VertexBuffer.UV5Kind
  31853. * - BABYLON.VertexBuffer.UV6Kind
  31854. * - BABYLON.VertexBuffer.ColorKind
  31855. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31856. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31857. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31858. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31859. */
  31860. Mesh.prototype.getVertexBuffer = function (kind) {
  31861. if (!this._geometry) {
  31862. return null;
  31863. }
  31864. return this._geometry.getVertexBuffer(kind);
  31865. };
  31866. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31867. if (!this._geometry) {
  31868. if (this._delayInfo) {
  31869. return this._delayInfo.indexOf(kind) !== -1;
  31870. }
  31871. return false;
  31872. }
  31873. return this._geometry.isVerticesDataPresent(kind);
  31874. };
  31875. /**
  31876. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31877. * Possible `kind` values :
  31878. * - BABYLON.VertexBuffer.PositionKind
  31879. * - BABYLON.VertexBuffer.UVKind
  31880. * - BABYLON.VertexBuffer.UV2Kind
  31881. * - BABYLON.VertexBuffer.UV3Kind
  31882. * - BABYLON.VertexBuffer.UV4Kind
  31883. * - BABYLON.VertexBuffer.UV5Kind
  31884. * - BABYLON.VertexBuffer.UV6Kind
  31885. * - BABYLON.VertexBuffer.ColorKind
  31886. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31887. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31888. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31889. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31890. */
  31891. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31892. if (!this._geometry) {
  31893. if (this._delayInfo) {
  31894. return this._delayInfo.indexOf(kind) !== -1;
  31895. }
  31896. return false;
  31897. }
  31898. return this._geometry.isVertexBufferUpdatable(kind);
  31899. };
  31900. /**
  31901. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31902. * Possible `kind` values :
  31903. * - BABYLON.VertexBuffer.PositionKind
  31904. * - BABYLON.VertexBuffer.UVKind
  31905. * - BABYLON.VertexBuffer.UV2Kind
  31906. * - BABYLON.VertexBuffer.UV3Kind
  31907. * - BABYLON.VertexBuffer.UV4Kind
  31908. * - BABYLON.VertexBuffer.UV5Kind
  31909. * - BABYLON.VertexBuffer.UV6Kind
  31910. * - BABYLON.VertexBuffer.ColorKind
  31911. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31912. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31913. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31914. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31915. */
  31916. Mesh.prototype.getVerticesDataKinds = function () {
  31917. if (!this._geometry) {
  31918. var result = new Array();
  31919. if (this._delayInfo) {
  31920. this._delayInfo.forEach(function (kind, index, array) {
  31921. result.push(kind);
  31922. });
  31923. }
  31924. return result;
  31925. }
  31926. return this._geometry.getVerticesDataKinds();
  31927. };
  31928. /**
  31929. * Returns a positive integer : the total number of indices in this mesh geometry.
  31930. * Returns zero if the mesh has no geometry.
  31931. */
  31932. Mesh.prototype.getTotalIndices = function () {
  31933. if (!this._geometry) {
  31934. return 0;
  31935. }
  31936. return this._geometry.getTotalIndices();
  31937. };
  31938. /**
  31939. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31940. * 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.
  31941. * Returns an empty array if the mesh has no geometry.
  31942. */
  31943. Mesh.prototype.getIndices = function (copyWhenShared) {
  31944. if (!this._geometry) {
  31945. return [];
  31946. }
  31947. return this._geometry.getIndices(copyWhenShared);
  31948. };
  31949. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31950. get: function () {
  31951. return this._masterMesh !== null && this._masterMesh !== undefined;
  31952. },
  31953. enumerable: true,
  31954. configurable: true
  31955. });
  31956. /**
  31957. * Determine if the current mesh is ready to be rendered
  31958. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31959. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31960. * @returns true if all associated assets are ready (material, textures, shaders)
  31961. */
  31962. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31963. if (completeCheck === void 0) { completeCheck = false; }
  31964. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31965. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31966. return false;
  31967. }
  31968. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31969. return false;
  31970. }
  31971. if (!this.subMeshes || this.subMeshes.length === 0) {
  31972. return true;
  31973. }
  31974. if (!completeCheck) {
  31975. return true;
  31976. }
  31977. var engine = this.getEngine();
  31978. var scene = this.getScene();
  31979. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31980. this.computeWorldMatrix();
  31981. var mat = this.material || scene.defaultMaterial;
  31982. if (mat) {
  31983. if (mat.storeEffectOnSubMeshes) {
  31984. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31985. var subMesh = _a[_i];
  31986. var effectiveMaterial = subMesh.getMaterial();
  31987. if (effectiveMaterial) {
  31988. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31989. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31990. return false;
  31991. }
  31992. }
  31993. else {
  31994. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31995. return false;
  31996. }
  31997. }
  31998. }
  31999. }
  32000. }
  32001. else {
  32002. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32003. return false;
  32004. }
  32005. }
  32006. }
  32007. // Shadows
  32008. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32009. var light = _c[_b];
  32010. var generator = light.getShadowGenerator();
  32011. if (generator) {
  32012. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32013. var subMesh = _e[_d];
  32014. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32015. return false;
  32016. }
  32017. }
  32018. }
  32019. }
  32020. // LOD
  32021. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32022. var lod = _g[_f];
  32023. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32024. return false;
  32025. }
  32026. }
  32027. return true;
  32028. };
  32029. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32030. /**
  32031. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  32032. * This property is pertinent only for updatable parametric shapes.
  32033. */
  32034. get: function () {
  32035. return this._areNormalsFrozen;
  32036. },
  32037. enumerable: true,
  32038. configurable: true
  32039. });
  32040. /**
  32041. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32042. * It has no effect at all on other shapes.
  32043. * It prevents the mesh normals from being recomputed on next `positions` array update.
  32044. * Returns the Mesh.
  32045. */
  32046. Mesh.prototype.freezeNormals = function () {
  32047. this._areNormalsFrozen = true;
  32048. return this;
  32049. };
  32050. /**
  32051. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32052. * It has no effect at all on other shapes.
  32053. * It reactivates the mesh normals computation if it was previously frozen.
  32054. * Returns the Mesh.
  32055. */
  32056. Mesh.prototype.unfreezeNormals = function () {
  32057. this._areNormalsFrozen = false;
  32058. return this;
  32059. };
  32060. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32061. /**
  32062. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32063. */
  32064. set: function (count) {
  32065. this._overridenInstanceCount = count;
  32066. },
  32067. enumerable: true,
  32068. configurable: true
  32069. });
  32070. // Methods
  32071. Mesh.prototype._preActivate = function () {
  32072. var sceneRenderId = this.getScene().getRenderId();
  32073. if (this._preActivateId === sceneRenderId) {
  32074. return this;
  32075. }
  32076. this._preActivateId = sceneRenderId;
  32077. this._visibleInstances = null;
  32078. return this;
  32079. };
  32080. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32081. if (this._visibleInstances) {
  32082. this._visibleInstances.intermediateDefaultRenderId = renderId;
  32083. }
  32084. return this;
  32085. };
  32086. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32087. if (!this._visibleInstances) {
  32088. this._visibleInstances = {};
  32089. this._visibleInstances.defaultRenderId = renderId;
  32090. this._visibleInstances.selfDefaultRenderId = this._renderId;
  32091. }
  32092. if (!this._visibleInstances[renderId]) {
  32093. this._visibleInstances[renderId] = new Array();
  32094. }
  32095. this._visibleInstances[renderId].push(instance);
  32096. return this;
  32097. };
  32098. /**
  32099. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32100. * This means the mesh underlying bounding box and sphere are recomputed.
  32101. * Returns the Mesh.
  32102. */
  32103. Mesh.prototype.refreshBoundingInfo = function () {
  32104. return this._refreshBoundingInfo(false);
  32105. };
  32106. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32107. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32108. return this;
  32109. }
  32110. var data = this._getPositionData(applySkeleton);
  32111. if (data) {
  32112. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32113. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32114. }
  32115. if (this.subMeshes) {
  32116. for (var index = 0; index < this.subMeshes.length; index++) {
  32117. this.subMeshes[index].refreshBoundingInfo();
  32118. }
  32119. }
  32120. this._updateBoundingInfo();
  32121. return this;
  32122. };
  32123. Mesh.prototype._getPositionData = function (applySkeleton) {
  32124. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32125. if (data && applySkeleton && this.skeleton) {
  32126. data = BABYLON.Tools.Slice(data);
  32127. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32128. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32129. if (matricesWeightsData && matricesIndicesData) {
  32130. var needExtras = this.numBoneInfluencers > 4;
  32131. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32132. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32133. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32134. var tempVector = BABYLON.Tmp.Vector3[0];
  32135. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32136. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32137. var matWeightIdx = 0;
  32138. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32139. finalMatrix.reset();
  32140. var inf;
  32141. var weight;
  32142. for (inf = 0; inf < 4; inf++) {
  32143. weight = matricesWeightsData[matWeightIdx + inf];
  32144. if (weight <= 0)
  32145. break;
  32146. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32147. finalMatrix.addToSelf(tempMatrix);
  32148. }
  32149. if (needExtras) {
  32150. for (inf = 0; inf < 4; inf++) {
  32151. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32152. if (weight <= 0)
  32153. break;
  32154. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32155. finalMatrix.addToSelf(tempMatrix);
  32156. }
  32157. }
  32158. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32159. tempVector.toArray(data, index);
  32160. }
  32161. }
  32162. }
  32163. return data;
  32164. };
  32165. Mesh.prototype._createGlobalSubMesh = function (force) {
  32166. var totalVertices = this.getTotalVertices();
  32167. if (!totalVertices || !this.getIndices()) {
  32168. return null;
  32169. }
  32170. // Check if we need to recreate the submeshes
  32171. if (this.subMeshes && this.subMeshes.length > 0) {
  32172. var ib = this.getIndices();
  32173. if (!ib) {
  32174. return null;
  32175. }
  32176. var totalIndices = ib.length;
  32177. var needToRecreate = false;
  32178. if (force) {
  32179. needToRecreate = true;
  32180. }
  32181. else {
  32182. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32183. var submesh = _a[_i];
  32184. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32185. needToRecreate = true;
  32186. break;
  32187. }
  32188. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32189. needToRecreate = true;
  32190. break;
  32191. }
  32192. }
  32193. }
  32194. if (!needToRecreate) {
  32195. return this.subMeshes[0];
  32196. }
  32197. }
  32198. this.releaseSubMeshes();
  32199. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32200. };
  32201. Mesh.prototype.subdivide = function (count) {
  32202. if (count < 1) {
  32203. return;
  32204. }
  32205. var totalIndices = this.getTotalIndices();
  32206. var subdivisionSize = (totalIndices / count) | 0;
  32207. var offset = 0;
  32208. // Ensure that subdivisionSize is a multiple of 3
  32209. while (subdivisionSize % 3 !== 0) {
  32210. subdivisionSize++;
  32211. }
  32212. this.releaseSubMeshes();
  32213. for (var index = 0; index < count; index++) {
  32214. if (offset >= totalIndices) {
  32215. break;
  32216. }
  32217. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32218. offset += subdivisionSize;
  32219. }
  32220. this.synchronizeInstances();
  32221. };
  32222. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32223. if (updatable === void 0) { updatable = false; }
  32224. if (!this._geometry) {
  32225. var vertexData = new BABYLON.VertexData();
  32226. vertexData.set(data, kind);
  32227. var scene = this.getScene();
  32228. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32229. }
  32230. else {
  32231. this._geometry.setVerticesData(kind, data, updatable, stride);
  32232. }
  32233. return this;
  32234. };
  32235. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32236. if (updatable === void 0) { updatable = true; }
  32237. var vb = this.getVertexBuffer(kind);
  32238. if (!vb || vb.isUpdatable() === updatable) {
  32239. return;
  32240. }
  32241. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32242. };
  32243. /**
  32244. * Sets the mesh VertexBuffer.
  32245. * Returns the Mesh.
  32246. */
  32247. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32248. if (!this._geometry) {
  32249. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32250. }
  32251. this._geometry.setVerticesBuffer(buffer);
  32252. return this;
  32253. };
  32254. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32255. if (!this._geometry) {
  32256. return this;
  32257. }
  32258. if (!makeItUnique) {
  32259. this._geometry.updateVerticesData(kind, data, updateExtends);
  32260. }
  32261. else {
  32262. this.makeGeometryUnique();
  32263. this.updateVerticesData(kind, data, updateExtends, false);
  32264. }
  32265. return this;
  32266. };
  32267. /**
  32268. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32269. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32270. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32271. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32272. * Returns the Mesh.
  32273. */
  32274. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32275. if (computeNormals === void 0) { computeNormals = true; }
  32276. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32277. if (!positions) {
  32278. return this;
  32279. }
  32280. positionFunction(positions);
  32281. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32282. if (computeNormals) {
  32283. var indices = this.getIndices();
  32284. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32285. if (!normals) {
  32286. return this;
  32287. }
  32288. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32289. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32290. }
  32291. return this;
  32292. };
  32293. /**
  32294. * Creates a un-shared specific occurence of the geometry for the mesh.
  32295. * Returns the Mesh.
  32296. */
  32297. Mesh.prototype.makeGeometryUnique = function () {
  32298. if (!this._geometry) {
  32299. return this;
  32300. }
  32301. var oldGeometry = this._geometry;
  32302. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32303. oldGeometry.releaseForMesh(this, true);
  32304. geometry.applyToMesh(this);
  32305. return this;
  32306. };
  32307. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32308. if (totalVertices === void 0) { totalVertices = null; }
  32309. if (updatable === void 0) { updatable = false; }
  32310. if (!this._geometry) {
  32311. var vertexData = new BABYLON.VertexData();
  32312. vertexData.indices = indices;
  32313. var scene = this.getScene();
  32314. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32315. }
  32316. else {
  32317. this._geometry.setIndices(indices, totalVertices, updatable);
  32318. }
  32319. return this;
  32320. };
  32321. /**
  32322. * Update the current index buffer
  32323. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32324. * Returns the Mesh.
  32325. */
  32326. Mesh.prototype.updateIndices = function (indices, offset) {
  32327. if (!this._geometry) {
  32328. return this;
  32329. }
  32330. this._geometry.updateIndices(indices, offset);
  32331. return this;
  32332. };
  32333. /**
  32334. * Invert the geometry to move from a right handed system to a left handed one.
  32335. * Returns the Mesh.
  32336. */
  32337. Mesh.prototype.toLeftHanded = function () {
  32338. if (!this._geometry) {
  32339. return this;
  32340. }
  32341. this._geometry.toLeftHanded();
  32342. return this;
  32343. };
  32344. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32345. if (!this._geometry) {
  32346. return this;
  32347. }
  32348. var engine = this.getScene().getEngine();
  32349. // Wireframe
  32350. var indexToBind;
  32351. if (this._unIndexed) {
  32352. indexToBind = null;
  32353. }
  32354. else {
  32355. switch (fillMode) {
  32356. case BABYLON.Material.PointFillMode:
  32357. indexToBind = null;
  32358. break;
  32359. case BABYLON.Material.WireFrameFillMode:
  32360. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32361. break;
  32362. default:
  32363. case BABYLON.Material.TriangleFillMode:
  32364. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32365. break;
  32366. }
  32367. }
  32368. // VBOs
  32369. this._geometry._bind(effect, indexToBind);
  32370. return this;
  32371. };
  32372. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32373. if (alternate === void 0) { alternate = false; }
  32374. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32375. return this;
  32376. }
  32377. this.onBeforeDrawObservable.notifyObservers(this);
  32378. var scene = this.getScene();
  32379. var engine = scene.getEngine();
  32380. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32381. // or triangles as points
  32382. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32383. }
  32384. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32385. // Triangles as wireframe
  32386. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32387. }
  32388. else {
  32389. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32390. }
  32391. if (scene._isAlternateRenderingEnabled && !alternate) {
  32392. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32393. if (!effect || !scene.activeCamera) {
  32394. return this;
  32395. }
  32396. scene._switchToAlternateCameraConfiguration(true);
  32397. this._effectiveMaterial.bindView(effect);
  32398. this._effectiveMaterial.bindViewProjection(effect);
  32399. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32400. this._draw(subMesh, fillMode, instancesCount, true);
  32401. engine.setViewport(scene.activeCamera.viewport);
  32402. scene._switchToAlternateCameraConfiguration(false);
  32403. this._effectiveMaterial.bindView(effect);
  32404. this._effectiveMaterial.bindViewProjection(effect);
  32405. }
  32406. return this;
  32407. };
  32408. /**
  32409. * Registers for this mesh a javascript function called just before the rendering process.
  32410. * This function is passed the current mesh.
  32411. * Return the Mesh.
  32412. */
  32413. Mesh.prototype.registerBeforeRender = function (func) {
  32414. this.onBeforeRenderObservable.add(func);
  32415. return this;
  32416. };
  32417. /**
  32418. * Disposes a previously registered javascript function called before the rendering.
  32419. * This function is passed the current mesh.
  32420. * Returns the Mesh.
  32421. */
  32422. Mesh.prototype.unregisterBeforeRender = function (func) {
  32423. this.onBeforeRenderObservable.removeCallback(func);
  32424. return this;
  32425. };
  32426. /**
  32427. * Registers for this mesh a javascript function called just after the rendering is complete.
  32428. * This function is passed the current mesh.
  32429. * Returns the Mesh.
  32430. */
  32431. Mesh.prototype.registerAfterRender = function (func) {
  32432. this.onAfterRenderObservable.add(func);
  32433. return this;
  32434. };
  32435. /**
  32436. * Disposes a previously registered javascript function called after the rendering.
  32437. * This function is passed the current mesh.
  32438. * Return the Mesh.
  32439. */
  32440. Mesh.prototype.unregisterAfterRender = function (func) {
  32441. this.onAfterRenderObservable.removeCallback(func);
  32442. return this;
  32443. };
  32444. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32445. var scene = this.getScene();
  32446. this._batchCache.mustReturn = false;
  32447. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32448. this._batchCache.visibleInstances[subMeshId] = null;
  32449. if (this._visibleInstances) {
  32450. var currentRenderId = scene.getRenderId();
  32451. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32452. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32453. var selfRenderId = this._renderId;
  32454. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32455. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32456. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32457. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32458. }
  32459. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32460. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32461. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32462. this._batchCache.mustReturn = true;
  32463. return this._batchCache;
  32464. }
  32465. if (currentRenderId !== selfRenderId) {
  32466. this._batchCache.renderSelf[subMeshId] = false;
  32467. }
  32468. }
  32469. this._renderIdForInstances[subMeshId] = currentRenderId;
  32470. }
  32471. return this._batchCache;
  32472. };
  32473. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32474. var visibleInstances = batch.visibleInstances[subMesh._id];
  32475. if (!visibleInstances) {
  32476. return this;
  32477. }
  32478. var matricesCount = visibleInstances.length + 1;
  32479. var bufferSize = matricesCount * 16 * 4;
  32480. var currentInstancesBufferSize = this._instancesBufferSize;
  32481. var instancesBuffer = this._instancesBuffer;
  32482. while (this._instancesBufferSize < bufferSize) {
  32483. this._instancesBufferSize *= 2;
  32484. }
  32485. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32486. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32487. }
  32488. var offset = 0;
  32489. var instancesCount = 0;
  32490. var world = this.getWorldMatrix();
  32491. if (batch.renderSelf[subMesh._id]) {
  32492. world.copyToArray(this._instancesData, offset);
  32493. offset += 16;
  32494. instancesCount++;
  32495. }
  32496. if (visibleInstances) {
  32497. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32498. var instance = visibleInstances[instanceIndex];
  32499. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32500. offset += 16;
  32501. instancesCount++;
  32502. }
  32503. }
  32504. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32505. if (instancesBuffer) {
  32506. instancesBuffer.dispose();
  32507. }
  32508. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32509. this._instancesBuffer = instancesBuffer;
  32510. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32511. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32512. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32513. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32514. }
  32515. else {
  32516. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32517. }
  32518. this._bind(subMesh, effect, fillMode);
  32519. this._draw(subMesh, fillMode, instancesCount);
  32520. engine.unbindInstanceAttributes();
  32521. return this;
  32522. };
  32523. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32524. var scene = this.getScene();
  32525. var engine = scene.getEngine();
  32526. if (hardwareInstancedRendering) {
  32527. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32528. }
  32529. else {
  32530. if (batch.renderSelf[subMesh._id]) {
  32531. // Draw
  32532. if (onBeforeDraw) {
  32533. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32534. }
  32535. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32536. }
  32537. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32538. if (visibleInstancesForSubMesh) {
  32539. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32540. var instance = visibleInstancesForSubMesh[instanceIndex];
  32541. // World
  32542. var world = instance.getWorldMatrix();
  32543. if (onBeforeDraw) {
  32544. onBeforeDraw(true, world, effectiveMaterial);
  32545. }
  32546. // Draw
  32547. this._draw(subMesh, fillMode);
  32548. }
  32549. }
  32550. }
  32551. return this;
  32552. };
  32553. /**
  32554. * Triggers the draw call for the mesh.
  32555. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32556. * Returns the Mesh.
  32557. */
  32558. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32559. this._checkOcclusionQuery();
  32560. if (this._isOccluded) {
  32561. return this;
  32562. }
  32563. var scene = this.getScene();
  32564. // Managing instances
  32565. var batch = this._getInstancesRenderList(subMesh._id);
  32566. if (batch.mustReturn) {
  32567. return this;
  32568. }
  32569. // Checking geometry state
  32570. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32571. return this;
  32572. }
  32573. this.onBeforeRenderObservable.notifyObservers(this);
  32574. var engine = scene.getEngine();
  32575. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32576. // Material
  32577. var material = subMesh.getMaterial();
  32578. if (!material) {
  32579. return this;
  32580. }
  32581. this._effectiveMaterial = material;
  32582. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32583. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32584. return this;
  32585. }
  32586. }
  32587. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32588. return this;
  32589. }
  32590. // Alpha mode
  32591. if (enableAlphaMode) {
  32592. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32593. }
  32594. // Outline - step 1
  32595. var savedDepthWrite = engine.getDepthWrite();
  32596. if (this.renderOutline) {
  32597. engine.setDepthWrite(false);
  32598. scene.getOutlineRenderer().render(subMesh, batch);
  32599. engine.setDepthWrite(savedDepthWrite);
  32600. }
  32601. var effect;
  32602. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32603. effect = subMesh.effect;
  32604. }
  32605. else {
  32606. effect = this._effectiveMaterial.getEffect();
  32607. }
  32608. if (!effect) {
  32609. return this;
  32610. }
  32611. var sideOrientation = this.overrideMaterialSideOrientation;
  32612. if (sideOrientation == null) {
  32613. sideOrientation = this._effectiveMaterial.sideOrientation;
  32614. if (this._getWorldMatrixDeterminant() < 0) {
  32615. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32616. }
  32617. }
  32618. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32619. if (this._effectiveMaterial.forceDepthWrite) {
  32620. engine.setDepthWrite(true);
  32621. }
  32622. // Bind
  32623. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32624. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32625. this._bind(subMesh, effect, fillMode);
  32626. }
  32627. var world = this.getWorldMatrix();
  32628. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32629. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32630. }
  32631. else {
  32632. this._effectiveMaterial.bind(world, this);
  32633. }
  32634. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32635. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32636. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32637. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32638. }
  32639. // Draw
  32640. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32641. // Unbind
  32642. this._effectiveMaterial.unbind();
  32643. // Outline - step 2
  32644. if (this.renderOutline && savedDepthWrite) {
  32645. engine.setDepthWrite(true);
  32646. engine.setColorWrite(false);
  32647. scene.getOutlineRenderer().render(subMesh, batch);
  32648. engine.setColorWrite(true);
  32649. }
  32650. // Overlay
  32651. if (this.renderOverlay) {
  32652. var currentMode = engine.getAlphaMode();
  32653. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32654. scene.getOutlineRenderer().render(subMesh, batch, true);
  32655. engine.setAlphaMode(currentMode);
  32656. }
  32657. this.onAfterRenderObservable.notifyObservers(this);
  32658. return this;
  32659. };
  32660. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32661. if (isInstance && effectiveMaterial) {
  32662. effectiveMaterial.bindOnlyWorldMatrix(world);
  32663. }
  32664. };
  32665. /**
  32666. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32667. */
  32668. Mesh.prototype.getEmittedParticleSystems = function () {
  32669. var results = new Array();
  32670. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32671. var particleSystem = this.getScene().particleSystems[index];
  32672. if (particleSystem.emitter === this) {
  32673. results.push(particleSystem);
  32674. }
  32675. }
  32676. return results;
  32677. };
  32678. /**
  32679. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32680. */
  32681. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32682. var results = new Array();
  32683. var descendants = this.getDescendants();
  32684. descendants.push(this);
  32685. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32686. var particleSystem = this.getScene().particleSystems[index];
  32687. var emitter = particleSystem.emitter;
  32688. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32689. results.push(particleSystem);
  32690. }
  32691. }
  32692. return results;
  32693. };
  32694. /**
  32695. * Normalize matrix weights so that all vertices have a total weight set to 1
  32696. */
  32697. Mesh.prototype.cleanMatrixWeights = function () {
  32698. var epsilon = 1e-3;
  32699. var noInfluenceBoneIndex = 0.0;
  32700. if (this.skeleton) {
  32701. noInfluenceBoneIndex = this.skeleton.bones.length;
  32702. }
  32703. else {
  32704. return;
  32705. }
  32706. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32707. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32708. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32709. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32710. var influencers = this.numBoneInfluencers;
  32711. var size = matricesWeights.length;
  32712. for (var i = 0; i < size; i += 4) {
  32713. var weight = 0.0;
  32714. var firstZeroWeight = -1;
  32715. for (var j = 0; j < 4; j++) {
  32716. var w = matricesWeights[i + j];
  32717. weight += w;
  32718. if (w < epsilon && firstZeroWeight < 0) {
  32719. firstZeroWeight = j;
  32720. }
  32721. }
  32722. if (matricesWeightsExtra) {
  32723. for (var j = 0; j < 4; j++) {
  32724. var w = matricesWeightsExtra[i + j];
  32725. weight += w;
  32726. if (w < epsilon && firstZeroWeight < 0) {
  32727. firstZeroWeight = j + 4;
  32728. }
  32729. }
  32730. }
  32731. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32732. firstZeroWeight = influencers - 1;
  32733. }
  32734. if (weight > epsilon) {
  32735. var mweight = 1.0 / weight;
  32736. for (var j = 0; j < 4; j++) {
  32737. matricesWeights[i + j] *= mweight;
  32738. }
  32739. if (matricesWeightsExtra) {
  32740. for (var j = 0; j < 4; j++) {
  32741. matricesWeightsExtra[i + j] *= mweight;
  32742. }
  32743. }
  32744. }
  32745. else {
  32746. if (firstZeroWeight >= 4) {
  32747. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32748. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32749. }
  32750. else {
  32751. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32752. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32753. }
  32754. }
  32755. }
  32756. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32757. if (matricesIndicesExtra) {
  32758. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32759. }
  32760. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32761. if (matricesWeightsExtra) {
  32762. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32763. }
  32764. };
  32765. Mesh.prototype._checkDelayState = function () {
  32766. var scene = this.getScene();
  32767. if (this._geometry) {
  32768. this._geometry.load(scene);
  32769. }
  32770. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32771. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32772. this._queueLoad(scene);
  32773. }
  32774. return this;
  32775. };
  32776. Mesh.prototype._queueLoad = function (scene) {
  32777. var _this = this;
  32778. scene._addPendingData(this);
  32779. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32780. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32781. if (data instanceof ArrayBuffer) {
  32782. _this._delayLoadingFunction(data, _this);
  32783. }
  32784. else {
  32785. _this._delayLoadingFunction(JSON.parse(data), _this);
  32786. }
  32787. _this.instances.forEach(function (instance) {
  32788. instance._syncSubMeshes();
  32789. });
  32790. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32791. scene._removePendingData(_this);
  32792. }, function () { }, scene.database, getBinaryData);
  32793. return this;
  32794. };
  32795. /**
  32796. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32797. */
  32798. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32799. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32800. return false;
  32801. }
  32802. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32803. return false;
  32804. }
  32805. this._checkDelayState();
  32806. return true;
  32807. };
  32808. /**
  32809. * Sets the mesh material by the material or multiMaterial `id` property.
  32810. * The material `id` is a string identifying the material or the multiMaterial.
  32811. * This method returns the Mesh.
  32812. */
  32813. Mesh.prototype.setMaterialByID = function (id) {
  32814. var materials = this.getScene().materials;
  32815. var index;
  32816. for (index = materials.length - 1; index > -1; index--) {
  32817. if (materials[index].id === id) {
  32818. this.material = materials[index];
  32819. return this;
  32820. }
  32821. }
  32822. // Multi
  32823. var multiMaterials = this.getScene().multiMaterials;
  32824. for (index = multiMaterials.length - 1; index > -1; index--) {
  32825. if (multiMaterials[index].id === id) {
  32826. this.material = multiMaterials[index];
  32827. return this;
  32828. }
  32829. }
  32830. return this;
  32831. };
  32832. /**
  32833. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32834. */
  32835. Mesh.prototype.getAnimatables = function () {
  32836. var results = new Array();
  32837. if (this.material) {
  32838. results.push(this.material);
  32839. }
  32840. if (this.skeleton) {
  32841. results.push(this.skeleton);
  32842. }
  32843. return results;
  32844. };
  32845. /**
  32846. * Modifies the mesh geometry according to the passed transformation matrix.
  32847. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32848. * The mesh normals are modified accordingly the same transformation.
  32849. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32850. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32851. * Returns the Mesh.
  32852. */
  32853. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32854. // Position
  32855. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32856. return this;
  32857. }
  32858. var submeshes = this.subMeshes.splice(0);
  32859. this._resetPointsArrayCache();
  32860. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32861. var temp = new Array();
  32862. var index;
  32863. for (index = 0; index < data.length; index += 3) {
  32864. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32865. }
  32866. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32867. // Normals
  32868. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32869. return this;
  32870. }
  32871. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32872. temp = [];
  32873. for (index = 0; index < data.length; index += 3) {
  32874. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32875. }
  32876. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32877. // flip faces?
  32878. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32879. this.flipFaces();
  32880. }
  32881. // Restore submeshes
  32882. this.releaseSubMeshes();
  32883. this.subMeshes = submeshes;
  32884. return this;
  32885. };
  32886. /**
  32887. * Modifies the mesh geometry according to its own current World Matrix.
  32888. * The mesh World Matrix is then reset.
  32889. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32890. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32891. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32892. * Returns the Mesh.
  32893. */
  32894. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32895. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32896. this.scaling.copyFromFloats(1, 1, 1);
  32897. this.position.copyFromFloats(0, 0, 0);
  32898. this.rotation.copyFromFloats(0, 0, 0);
  32899. //only if quaternion is already set
  32900. if (this.rotationQuaternion) {
  32901. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32902. }
  32903. this._worldMatrix = BABYLON.Matrix.Identity();
  32904. return this;
  32905. };
  32906. Object.defineProperty(Mesh.prototype, "_positions", {
  32907. // Cache
  32908. get: function () {
  32909. if (this._geometry) {
  32910. return this._geometry._positions;
  32911. }
  32912. return null;
  32913. },
  32914. enumerable: true,
  32915. configurable: true
  32916. });
  32917. Mesh.prototype._resetPointsArrayCache = function () {
  32918. if (this._geometry) {
  32919. this._geometry._resetPointsArrayCache();
  32920. }
  32921. return this;
  32922. };
  32923. Mesh.prototype._generatePointsArray = function () {
  32924. if (this._geometry) {
  32925. return this._geometry._generatePointsArray();
  32926. }
  32927. return false;
  32928. };
  32929. /**
  32930. * Returns a new Mesh object generated from the current mesh properties.
  32931. * This method must not get confused with createInstance().
  32932. * The parameter `name` is a string, the name given to the new mesh.
  32933. * The optional parameter `newParent` can be any Node object (default `null`).
  32934. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32935. * 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.
  32936. */
  32937. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32938. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32939. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32940. };
  32941. /**
  32942. * Releases resources associated with this mesh.
  32943. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32944. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32945. */
  32946. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32947. var _this = this;
  32948. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32949. this.morphTargetManager = null;
  32950. if (this._geometry) {
  32951. this._geometry.releaseForMesh(this, true);
  32952. }
  32953. // Sources
  32954. var meshes = this.getScene().meshes;
  32955. meshes.forEach(function (abstractMesh) {
  32956. var mesh = abstractMesh;
  32957. if (mesh._source && mesh._source === _this) {
  32958. mesh._source = null;
  32959. }
  32960. });
  32961. this._source = null;
  32962. // Instances
  32963. if (this._instancesBuffer) {
  32964. this._instancesBuffer.dispose();
  32965. this._instancesBuffer = null;
  32966. }
  32967. while (this.instances.length) {
  32968. this.instances[0].dispose();
  32969. }
  32970. // Effect layers.
  32971. var effectLayers = this.getScene().effectLayers;
  32972. for (var i = 0; i < effectLayers.length; i++) {
  32973. var effectLayer = effectLayers[i];
  32974. if (effectLayer) {
  32975. effectLayer._disposeMesh(this);
  32976. }
  32977. }
  32978. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32979. };
  32980. /**
  32981. * Modifies the mesh geometry according to a displacement map.
  32982. * 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.
  32983. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32984. * This method returns nothing.
  32985. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32986. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32987. * 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.
  32988. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32989. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32990. *
  32991. * Returns the Mesh.
  32992. */
  32993. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32994. var _this = this;
  32995. var scene = this.getScene();
  32996. var onload = function (img) {
  32997. // Getting height map data
  32998. var canvas = document.createElement("canvas");
  32999. var context = canvas.getContext("2d");
  33000. var heightMapWidth = img.width;
  33001. var heightMapHeight = img.height;
  33002. canvas.width = heightMapWidth;
  33003. canvas.height = heightMapHeight;
  33004. context.drawImage(img, 0, 0);
  33005. // Create VertexData from map data
  33006. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33007. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33008. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  33009. //execute success callback, if set
  33010. if (onSuccess) {
  33011. onSuccess(_this);
  33012. }
  33013. };
  33014. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33015. return this;
  33016. };
  33017. /**
  33018. * Modifies the mesh geometry according to a displacementMap buffer.
  33019. * 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.
  33020. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33021. * This method returns nothing.
  33022. * 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.
  33023. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  33024. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33025. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33026. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33027. *
  33028. * Returns the Mesh.
  33029. */
  33030. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  33031. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33032. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33033. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33034. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33035. return this;
  33036. }
  33037. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33038. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33039. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33040. var position = BABYLON.Vector3.Zero();
  33041. var normal = BABYLON.Vector3.Zero();
  33042. var uv = BABYLON.Vector2.Zero();
  33043. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33044. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33045. for (var index = 0; index < positions.length; index += 3) {
  33046. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33047. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33048. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33049. // Compute height
  33050. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33051. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33052. var pos = (u + v * heightMapWidth) * 4;
  33053. var r = buffer[pos] / 255.0;
  33054. var g = buffer[pos + 1] / 255.0;
  33055. var b = buffer[pos + 2] / 255.0;
  33056. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33057. normal.normalize();
  33058. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33059. position = position.add(normal);
  33060. position.toArray(positions, index);
  33061. }
  33062. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33063. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33064. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33065. return this;
  33066. };
  33067. /**
  33068. * Modify the mesh to get a flat shading rendering.
  33069. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33070. * This method returns the Mesh.
  33071. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33072. */
  33073. Mesh.prototype.convertToFlatShadedMesh = function () {
  33074. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  33075. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33076. var kinds = this.getVerticesDataKinds();
  33077. var vbs = {};
  33078. var data = {};
  33079. var newdata = {};
  33080. var updatableNormals = false;
  33081. var kindIndex;
  33082. var kind;
  33083. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33084. kind = kinds[kindIndex];
  33085. var vertexBuffer = this.getVertexBuffer(kind);
  33086. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33087. updatableNormals = vertexBuffer.isUpdatable();
  33088. kinds.splice(kindIndex, 1);
  33089. kindIndex--;
  33090. continue;
  33091. }
  33092. vbs[kind] = vertexBuffer;
  33093. data[kind] = vbs[kind].getData();
  33094. newdata[kind] = [];
  33095. }
  33096. // Save previous submeshes
  33097. var previousSubmeshes = this.subMeshes.slice(0);
  33098. var indices = this.getIndices();
  33099. var totalIndices = this.getTotalIndices();
  33100. // Generating unique vertices per face
  33101. var index;
  33102. for (index = 0; index < totalIndices; index++) {
  33103. var vertexIndex = indices[index];
  33104. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33105. kind = kinds[kindIndex];
  33106. var stride = vbs[kind].getStrideSize();
  33107. for (var offset = 0; offset < stride; offset++) {
  33108. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33109. }
  33110. }
  33111. }
  33112. // Updating faces & normal
  33113. var normals = [];
  33114. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33115. for (index = 0; index < totalIndices; index += 3) {
  33116. indices[index] = index;
  33117. indices[index + 1] = index + 1;
  33118. indices[index + 2] = index + 2;
  33119. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33120. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33121. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33122. var p1p2 = p1.subtract(p2);
  33123. var p3p2 = p3.subtract(p2);
  33124. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33125. // Store same normals for every vertex
  33126. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33127. normals.push(normal.x);
  33128. normals.push(normal.y);
  33129. normals.push(normal.z);
  33130. }
  33131. }
  33132. this.setIndices(indices);
  33133. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33134. // Updating vertex buffers
  33135. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33136. kind = kinds[kindIndex];
  33137. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33138. }
  33139. // Updating submeshes
  33140. this.releaseSubMeshes();
  33141. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33142. var previousOne = previousSubmeshes[submeshIndex];
  33143. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33144. }
  33145. this.synchronizeInstances();
  33146. return this;
  33147. };
  33148. /**
  33149. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33150. * In other words, more vertices, no more indices and a single bigger VBO.
  33151. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33152. * Returns the Mesh.
  33153. */
  33154. Mesh.prototype.convertToUnIndexedMesh = function () {
  33155. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33156. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33157. var kinds = this.getVerticesDataKinds();
  33158. var vbs = {};
  33159. var data = {};
  33160. var newdata = {};
  33161. var kindIndex;
  33162. var kind;
  33163. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33164. kind = kinds[kindIndex];
  33165. var vertexBuffer = this.getVertexBuffer(kind);
  33166. vbs[kind] = vertexBuffer;
  33167. data[kind] = vbs[kind].getData();
  33168. newdata[kind] = [];
  33169. }
  33170. // Save previous submeshes
  33171. var previousSubmeshes = this.subMeshes.slice(0);
  33172. var indices = this.getIndices();
  33173. var totalIndices = this.getTotalIndices();
  33174. // Generating unique vertices per face
  33175. var index;
  33176. for (index = 0; index < totalIndices; index++) {
  33177. var vertexIndex = indices[index];
  33178. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33179. kind = kinds[kindIndex];
  33180. var stride = vbs[kind].getStrideSize();
  33181. for (var offset = 0; offset < stride; offset++) {
  33182. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33183. }
  33184. }
  33185. }
  33186. // Updating indices
  33187. for (index = 0; index < totalIndices; index += 3) {
  33188. indices[index] = index;
  33189. indices[index + 1] = index + 1;
  33190. indices[index + 2] = index + 2;
  33191. }
  33192. this.setIndices(indices);
  33193. // Updating vertex buffers
  33194. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33195. kind = kinds[kindIndex];
  33196. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33197. }
  33198. // Updating submeshes
  33199. this.releaseSubMeshes();
  33200. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33201. var previousOne = previousSubmeshes[submeshIndex];
  33202. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33203. }
  33204. this._unIndexed = true;
  33205. this.synchronizeInstances();
  33206. return this;
  33207. };
  33208. /**
  33209. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33210. * This method returns the Mesh.
  33211. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33212. */
  33213. Mesh.prototype.flipFaces = function (flipNormals) {
  33214. if (flipNormals === void 0) { flipNormals = false; }
  33215. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33216. var i;
  33217. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33218. for (i = 0; i < vertex_data.normals.length; i++) {
  33219. vertex_data.normals[i] *= -1;
  33220. }
  33221. }
  33222. if (vertex_data.indices) {
  33223. var temp;
  33224. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33225. // reassign indices
  33226. temp = vertex_data.indices[i + 1];
  33227. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33228. vertex_data.indices[i + 2] = temp;
  33229. }
  33230. }
  33231. vertex_data.applyToMesh(this);
  33232. return this;
  33233. };
  33234. // Instances
  33235. /**
  33236. * Creates a new InstancedMesh object from the mesh model.
  33237. * An instance shares the same properties and the same material than its model.
  33238. * Only these properties of each instance can then be set individually :
  33239. * - position
  33240. * - rotation
  33241. * - rotationQuaternion
  33242. * - setPivotMatrix
  33243. * - scaling
  33244. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33245. * Warning : this method is not supported for Line mesh and LineSystem
  33246. */
  33247. Mesh.prototype.createInstance = function (name) {
  33248. return new BABYLON.InstancedMesh(name, this);
  33249. };
  33250. /**
  33251. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33252. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33253. * This method returns the Mesh.
  33254. */
  33255. Mesh.prototype.synchronizeInstances = function () {
  33256. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33257. var instance = this.instances[instanceIndex];
  33258. instance._syncSubMeshes();
  33259. }
  33260. return this;
  33261. };
  33262. /**
  33263. * Simplify the mesh according to the given array of settings.
  33264. * Function will return immediately and will simplify async. It returns the Mesh.
  33265. * @param settings a collection of simplification settings.
  33266. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33267. * @param type the type of simplification to run.
  33268. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33269. */
  33270. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33271. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33272. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33273. this.getScene().simplificationQueue.addTask({
  33274. settings: settings,
  33275. parallelProcessing: parallelProcessing,
  33276. mesh: this,
  33277. simplificationType: simplificationType,
  33278. successCallback: successCallback
  33279. });
  33280. return this;
  33281. };
  33282. /**
  33283. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33284. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33285. * This should be used together with the simplification to avoid disappearing triangles.
  33286. * Returns the Mesh.
  33287. * @param successCallback an optional success callback to be called after the optimization finished.
  33288. */
  33289. Mesh.prototype.optimizeIndices = function (successCallback) {
  33290. var _this = this;
  33291. var indices = this.getIndices();
  33292. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33293. if (!positions || !indices) {
  33294. return this;
  33295. }
  33296. var vectorPositions = new Array();
  33297. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33298. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33299. }
  33300. var dupes = new Array();
  33301. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33302. var realPos = vectorPositions.length - 1 - iteration;
  33303. var testedPosition = vectorPositions[realPos];
  33304. for (var j = 0; j < realPos; ++j) {
  33305. var againstPosition = vectorPositions[j];
  33306. if (testedPosition.equals(againstPosition)) {
  33307. dupes[realPos] = j;
  33308. break;
  33309. }
  33310. }
  33311. }, function () {
  33312. for (var i = 0; i < indices.length; ++i) {
  33313. indices[i] = dupes[indices[i]] || indices[i];
  33314. }
  33315. //indices are now reordered
  33316. var originalSubMeshes = _this.subMeshes.slice(0);
  33317. _this.setIndices(indices);
  33318. _this.subMeshes = originalSubMeshes;
  33319. if (successCallback) {
  33320. successCallback(_this);
  33321. }
  33322. });
  33323. return this;
  33324. };
  33325. Mesh.prototype.serialize = function (serializationObject) {
  33326. serializationObject.name = this.name;
  33327. serializationObject.id = this.id;
  33328. serializationObject.type = this.getClassName();
  33329. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33330. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33331. }
  33332. serializationObject.position = this.position.asArray();
  33333. if (this.rotationQuaternion) {
  33334. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33335. }
  33336. else if (this.rotation) {
  33337. serializationObject.rotation = this.rotation.asArray();
  33338. }
  33339. serializationObject.scaling = this.scaling.asArray();
  33340. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33341. serializationObject.isEnabled = this.isEnabled(false);
  33342. serializationObject.isVisible = this.isVisible;
  33343. serializationObject.infiniteDistance = this.infiniteDistance;
  33344. serializationObject.pickable = this.isPickable;
  33345. serializationObject.receiveShadows = this.receiveShadows;
  33346. serializationObject.billboardMode = this.billboardMode;
  33347. serializationObject.visibility = this.visibility;
  33348. serializationObject.checkCollisions = this.checkCollisions;
  33349. serializationObject.isBlocker = this.isBlocker;
  33350. // Parent
  33351. if (this.parent) {
  33352. serializationObject.parentId = this.parent.id;
  33353. }
  33354. // Geometry
  33355. serializationObject.isUnIndexed = this.isUnIndexed;
  33356. var geometry = this._geometry;
  33357. if (geometry) {
  33358. var geometryId = geometry.id;
  33359. serializationObject.geometryId = geometryId;
  33360. // SubMeshes
  33361. serializationObject.subMeshes = [];
  33362. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33363. var subMesh = this.subMeshes[subIndex];
  33364. serializationObject.subMeshes.push({
  33365. materialIndex: subMesh.materialIndex,
  33366. verticesStart: subMesh.verticesStart,
  33367. verticesCount: subMesh.verticesCount,
  33368. indexStart: subMesh.indexStart,
  33369. indexCount: subMesh.indexCount
  33370. });
  33371. }
  33372. }
  33373. // Material
  33374. if (this.material) {
  33375. serializationObject.materialId = this.material.id;
  33376. }
  33377. else {
  33378. this.material = null;
  33379. }
  33380. // Morph targets
  33381. if (this.morphTargetManager) {
  33382. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33383. }
  33384. // Skeleton
  33385. if (this.skeleton) {
  33386. serializationObject.skeletonId = this.skeleton.id;
  33387. }
  33388. // Physics
  33389. //TODO implement correct serialization for physics impostors.
  33390. var impostor = this.getPhysicsImpostor();
  33391. if (impostor) {
  33392. serializationObject.physicsMass = impostor.getParam("mass");
  33393. serializationObject.physicsFriction = impostor.getParam("friction");
  33394. serializationObject.physicsRestitution = impostor.getParam("mass");
  33395. serializationObject.physicsImpostor = impostor.type;
  33396. }
  33397. // Metadata
  33398. if (this.metadata) {
  33399. serializationObject.metadata = this.metadata;
  33400. }
  33401. // Instances
  33402. serializationObject.instances = [];
  33403. for (var index = 0; index < this.instances.length; index++) {
  33404. var instance = this.instances[index];
  33405. var serializationInstance = {
  33406. name: instance.name,
  33407. id: instance.id,
  33408. position: instance.position.asArray(),
  33409. scaling: instance.scaling.asArray()
  33410. };
  33411. if (instance.rotationQuaternion) {
  33412. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33413. }
  33414. else if (instance.rotation) {
  33415. serializationInstance.rotation = instance.rotation.asArray();
  33416. }
  33417. serializationObject.instances.push(serializationInstance);
  33418. // Animations
  33419. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33420. serializationInstance.ranges = instance.serializeAnimationRanges();
  33421. }
  33422. //
  33423. // Animations
  33424. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33425. serializationObject.ranges = this.serializeAnimationRanges();
  33426. // Layer mask
  33427. serializationObject.layerMask = this.layerMask;
  33428. // Alpha
  33429. serializationObject.alphaIndex = this.alphaIndex;
  33430. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33431. // Overlay
  33432. serializationObject.overlayAlpha = this.overlayAlpha;
  33433. serializationObject.overlayColor = this.overlayColor.asArray();
  33434. serializationObject.renderOverlay = this.renderOverlay;
  33435. // Fog
  33436. serializationObject.applyFog = this.applyFog;
  33437. // Action Manager
  33438. if (this.actionManager) {
  33439. serializationObject.actions = this.actionManager.serialize(this.name);
  33440. }
  33441. };
  33442. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33443. if (!this.geometry) {
  33444. return;
  33445. }
  33446. this._markSubMeshesAsAttributesDirty();
  33447. var morphTargetManager = this._morphTargetManager;
  33448. if (morphTargetManager && morphTargetManager.vertexCount) {
  33449. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33450. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33451. this.morphTargetManager = null;
  33452. return;
  33453. }
  33454. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33455. var morphTarget = morphTargetManager.getActiveTarget(index);
  33456. var positions = morphTarget.getPositions();
  33457. if (!positions) {
  33458. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33459. return;
  33460. }
  33461. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33462. var normals = morphTarget.getNormals();
  33463. if (normals) {
  33464. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33465. }
  33466. var tangents = morphTarget.getTangents();
  33467. if (tangents) {
  33468. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33469. }
  33470. }
  33471. }
  33472. else {
  33473. var index = 0;
  33474. // Positions
  33475. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33476. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33477. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33478. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33479. }
  33480. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33481. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33482. }
  33483. index++;
  33484. }
  33485. }
  33486. };
  33487. // Statics
  33488. /**
  33489. * Returns a new Mesh object parsed from the source provided.
  33490. * The parameter `parsedMesh` is the source.
  33491. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33492. */
  33493. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33494. var mesh;
  33495. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33496. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33497. }
  33498. else {
  33499. mesh = new Mesh(parsedMesh.name, scene);
  33500. }
  33501. mesh.id = parsedMesh.id;
  33502. if (BABYLON.Tags) {
  33503. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33504. }
  33505. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33506. if (parsedMesh.metadata !== undefined) {
  33507. mesh.metadata = parsedMesh.metadata;
  33508. }
  33509. if (parsedMesh.rotationQuaternion) {
  33510. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33511. }
  33512. else if (parsedMesh.rotation) {
  33513. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33514. }
  33515. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33516. if (parsedMesh.localMatrix) {
  33517. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33518. }
  33519. else if (parsedMesh.pivotMatrix) {
  33520. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33521. }
  33522. mesh.setEnabled(parsedMesh.isEnabled);
  33523. mesh.isVisible = parsedMesh.isVisible;
  33524. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33525. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33526. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33527. if (parsedMesh.applyFog !== undefined) {
  33528. mesh.applyFog = parsedMesh.applyFog;
  33529. }
  33530. if (parsedMesh.pickable !== undefined) {
  33531. mesh.isPickable = parsedMesh.pickable;
  33532. }
  33533. if (parsedMesh.alphaIndex !== undefined) {
  33534. mesh.alphaIndex = parsedMesh.alphaIndex;
  33535. }
  33536. mesh.receiveShadows = parsedMesh.receiveShadows;
  33537. mesh.billboardMode = parsedMesh.billboardMode;
  33538. if (parsedMesh.visibility !== undefined) {
  33539. mesh.visibility = parsedMesh.visibility;
  33540. }
  33541. mesh.checkCollisions = parsedMesh.checkCollisions;
  33542. if (parsedMesh.isBlocker !== undefined) {
  33543. mesh.isBlocker = parsedMesh.isBlocker;
  33544. }
  33545. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33546. // freezeWorldMatrix
  33547. if (parsedMesh.freezeWorldMatrix) {
  33548. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33549. }
  33550. // Parent
  33551. if (parsedMesh.parentId) {
  33552. mesh._waitingParentId = parsedMesh.parentId;
  33553. }
  33554. // Actions
  33555. if (parsedMesh.actions !== undefined) {
  33556. mesh._waitingActions = parsedMesh.actions;
  33557. }
  33558. // Overlay
  33559. if (parsedMesh.overlayAlpha !== undefined) {
  33560. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33561. }
  33562. if (parsedMesh.overlayColor !== undefined) {
  33563. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33564. }
  33565. if (parsedMesh.renderOverlay !== undefined) {
  33566. mesh.renderOverlay = parsedMesh.renderOverlay;
  33567. }
  33568. // Geometry
  33569. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33570. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33571. if (parsedMesh.delayLoadingFile) {
  33572. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33573. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33574. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33575. if (parsedMesh._binaryInfo) {
  33576. mesh._binaryInfo = parsedMesh._binaryInfo;
  33577. }
  33578. mesh._delayInfo = [];
  33579. if (parsedMesh.hasUVs) {
  33580. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33581. }
  33582. if (parsedMesh.hasUVs2) {
  33583. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33584. }
  33585. if (parsedMesh.hasUVs3) {
  33586. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33587. }
  33588. if (parsedMesh.hasUVs4) {
  33589. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33590. }
  33591. if (parsedMesh.hasUVs5) {
  33592. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33593. }
  33594. if (parsedMesh.hasUVs6) {
  33595. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33596. }
  33597. if (parsedMesh.hasColors) {
  33598. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33599. }
  33600. if (parsedMesh.hasMatricesIndices) {
  33601. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33602. }
  33603. if (parsedMesh.hasMatricesWeights) {
  33604. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33605. }
  33606. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33607. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33608. mesh._checkDelayState();
  33609. }
  33610. }
  33611. else {
  33612. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33613. }
  33614. // Material
  33615. if (parsedMesh.materialId) {
  33616. mesh.setMaterialByID(parsedMesh.materialId);
  33617. }
  33618. else {
  33619. mesh.material = null;
  33620. }
  33621. // Morph targets
  33622. if (parsedMesh.morphTargetManagerId > -1) {
  33623. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33624. }
  33625. // Skeleton
  33626. if (parsedMesh.skeletonId > -1) {
  33627. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33628. if (parsedMesh.numBoneInfluencers) {
  33629. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33630. }
  33631. }
  33632. // Animations
  33633. if (parsedMesh.animations) {
  33634. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33635. var parsedAnimation = parsedMesh.animations[animationIndex];
  33636. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33637. }
  33638. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33639. }
  33640. if (parsedMesh.autoAnimate) {
  33641. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33642. }
  33643. // Layer Mask
  33644. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33645. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33646. }
  33647. else {
  33648. mesh.layerMask = 0x0FFFFFFF;
  33649. }
  33650. // Physics
  33651. if (parsedMesh.physicsImpostor) {
  33652. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33653. mass: parsedMesh.physicsMass,
  33654. friction: parsedMesh.physicsFriction,
  33655. restitution: parsedMesh.physicsRestitution
  33656. }, scene);
  33657. }
  33658. // Instances
  33659. if (parsedMesh.instances) {
  33660. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33661. var parsedInstance = parsedMesh.instances[index];
  33662. var instance = mesh.createInstance(parsedInstance.name);
  33663. if (parsedInstance.id) {
  33664. instance.id = parsedInstance.id;
  33665. }
  33666. if (BABYLON.Tags) {
  33667. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33668. }
  33669. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33670. if (parsedInstance.parentId) {
  33671. instance._waitingParentId = parsedInstance.parentId;
  33672. }
  33673. if (parsedInstance.rotationQuaternion) {
  33674. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33675. }
  33676. else if (parsedInstance.rotation) {
  33677. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33678. }
  33679. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33680. instance.checkCollisions = mesh.checkCollisions;
  33681. if (parsedMesh.animations) {
  33682. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33683. parsedAnimation = parsedMesh.animations[animationIndex];
  33684. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33685. }
  33686. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33687. if (parsedMesh.autoAnimate) {
  33688. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33689. }
  33690. }
  33691. }
  33692. }
  33693. return mesh;
  33694. };
  33695. /**
  33696. * Creates a ribbon mesh.
  33697. * Please consider using the same method from the MeshBuilder class instead.
  33698. * 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.
  33699. *
  33700. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33701. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33702. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33703. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33704. * 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.
  33705. * 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.
  33706. * 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
  33707. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33708. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33709. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33710. */
  33711. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33712. if (closeArray === void 0) { closeArray = false; }
  33713. if (updatable === void 0) { updatable = false; }
  33714. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33715. pathArray: pathArray,
  33716. closeArray: closeArray,
  33717. closePath: closePath,
  33718. offset: offset,
  33719. updatable: updatable,
  33720. sideOrientation: sideOrientation,
  33721. instance: instance
  33722. }, scene);
  33723. };
  33724. /**
  33725. * Creates a plane polygonal mesh. By default, this is a disc.
  33726. * Please consider using the same method from the MeshBuilder class instead.
  33727. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33728. * 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.
  33729. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33730. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33731. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33732. */
  33733. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33734. if (scene === void 0) { scene = null; }
  33735. var options = {
  33736. radius: radius,
  33737. tessellation: tessellation,
  33738. sideOrientation: sideOrientation,
  33739. updatable: updatable
  33740. };
  33741. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33742. };
  33743. /**
  33744. * Creates a box mesh.
  33745. * Please consider using the same method from the MeshBuilder class instead.
  33746. * The parameter `size` sets the size (float) of each box side (default 1).
  33747. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33748. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33749. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33750. */
  33751. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33752. if (scene === void 0) { scene = null; }
  33753. var options = {
  33754. size: size,
  33755. sideOrientation: sideOrientation,
  33756. updatable: updatable
  33757. };
  33758. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33759. };
  33760. /**
  33761. * Creates a sphere mesh.
  33762. * Please consider using the same method from the MeshBuilder class instead.
  33763. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33764. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33765. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33766. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33767. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33768. */
  33769. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33770. var options = {
  33771. segments: segments,
  33772. diameterX: diameter,
  33773. diameterY: diameter,
  33774. diameterZ: diameter,
  33775. sideOrientation: sideOrientation,
  33776. updatable: updatable
  33777. };
  33778. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33779. };
  33780. /**
  33781. * Creates a cylinder or a cone mesh.
  33782. * Please consider using the same method from the MeshBuilder class instead.
  33783. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33784. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33785. * 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.
  33786. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33787. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33788. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33789. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33790. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33791. */
  33792. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33793. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33794. if (scene !== undefined) {
  33795. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33796. updatable = scene;
  33797. }
  33798. scene = subdivisions;
  33799. subdivisions = 1;
  33800. }
  33801. var options = {
  33802. height: height,
  33803. diameterTop: diameterTop,
  33804. diameterBottom: diameterBottom,
  33805. tessellation: tessellation,
  33806. subdivisions: subdivisions,
  33807. sideOrientation: sideOrientation,
  33808. updatable: updatable
  33809. };
  33810. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33811. };
  33812. // Torus (Code from SharpDX.org)
  33813. /**
  33814. * Creates a torus mesh.
  33815. * Please consider using the same method from the MeshBuilder class instead.
  33816. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33817. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33818. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33819. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33820. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33821. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33822. */
  33823. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33824. var options = {
  33825. diameter: diameter,
  33826. thickness: thickness,
  33827. tessellation: tessellation,
  33828. sideOrientation: sideOrientation,
  33829. updatable: updatable
  33830. };
  33831. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33832. };
  33833. /**
  33834. * Creates a torus knot mesh.
  33835. * Please consider using the same method from the MeshBuilder class instead.
  33836. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33837. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33838. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33839. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33840. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33841. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  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.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33845. var options = {
  33846. radius: radius,
  33847. tube: tube,
  33848. radialSegments: radialSegments,
  33849. tubularSegments: tubularSegments,
  33850. p: p,
  33851. q: q,
  33852. sideOrientation: sideOrientation,
  33853. updatable: updatable
  33854. };
  33855. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33856. };
  33857. /**
  33858. * Creates a line mesh.
  33859. * Please consider using the same method from the MeshBuilder class instead.
  33860. * 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.
  33861. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33862. * The parameter `points` is an array successive Vector3.
  33863. * 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
  33864. * When updating an instance, remember that only point positions can change, not the number of points.
  33865. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33866. */
  33867. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33868. if (scene === void 0) { scene = null; }
  33869. if (updatable === void 0) { updatable = false; }
  33870. if (instance === void 0) { instance = null; }
  33871. var options = {
  33872. points: points,
  33873. updatable: updatable,
  33874. instance: instance
  33875. };
  33876. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33877. };
  33878. /**
  33879. * Creates a dashed line mesh.
  33880. * Please consider using the same method from the MeshBuilder class instead.
  33881. * 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.
  33882. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33883. * The parameter `points` is an array successive Vector3.
  33884. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33885. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33886. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33887. * 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
  33888. * When updating an instance, remember that only point positions can change, not the number of points.
  33889. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33890. */
  33891. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33892. if (scene === void 0) { scene = null; }
  33893. var options = {
  33894. points: points,
  33895. dashSize: dashSize,
  33896. gapSize: gapSize,
  33897. dashNb: dashNb,
  33898. updatable: updatable,
  33899. instance: instance
  33900. };
  33901. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33902. };
  33903. /**
  33904. * Creates a polygon mesh.
  33905. * Please consider using the same method from the MeshBuilder class instead.
  33906. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33907. * 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.
  33908. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33909. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33910. * Remember you can only change the shape positions, not their number when updating a polygon.
  33911. */
  33912. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33913. var options = {
  33914. shape: shape,
  33915. holes: holes,
  33916. updatable: updatable,
  33917. sideOrientation: sideOrientation
  33918. };
  33919. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33920. };
  33921. /**
  33922. * Creates an extruded polygon mesh, with depth in the Y direction.
  33923. * Please consider using the same method from the MeshBuilder class instead.
  33924. */
  33925. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33926. var options = {
  33927. shape: shape,
  33928. holes: holes,
  33929. depth: depth,
  33930. updatable: updatable,
  33931. sideOrientation: sideOrientation
  33932. };
  33933. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33934. };
  33935. /**
  33936. * Creates an extruded shape mesh.
  33937. * 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.
  33938. * Please consider using the same method from the MeshBuilder class instead.
  33939. *
  33940. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33941. * 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
  33942. * extruded along the Z axis.
  33943. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33944. * 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.
  33945. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33946. * 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
  33947. * 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
  33948. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33949. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33950. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33951. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33952. */
  33953. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33954. if (scene === void 0) { scene = null; }
  33955. var options = {
  33956. shape: shape,
  33957. path: path,
  33958. scale: scale,
  33959. rotation: rotation,
  33960. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33961. sideOrientation: sideOrientation,
  33962. instance: instance,
  33963. updatable: updatable
  33964. };
  33965. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33966. };
  33967. /**
  33968. * Creates an custom extruded shape mesh.
  33969. * 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.
  33970. * Please consider using the same method from the MeshBuilder class instead.
  33971. *
  33972. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33973. * 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
  33974. * extruded along the Z axis.
  33975. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33976. * 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
  33977. * and the distance of this point from the begining of the path :
  33978. * ```javascript
  33979. * var rotationFunction = function(i, distance) {
  33980. * // do things
  33981. * return rotationValue; }
  33982. * ```
  33983. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33984. * 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
  33985. * and the distance of this point from the begining of the path :
  33986. * ```javascript
  33987. * var scaleFunction = function(i, distance) {
  33988. * // do things
  33989. * return scaleValue;}
  33990. * ```
  33991. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33992. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33993. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33994. * 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
  33995. * 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
  33996. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33997. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33998. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33999. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34000. */
  34001. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34002. var options = {
  34003. shape: shape,
  34004. path: path,
  34005. scaleFunction: scaleFunction,
  34006. rotationFunction: rotationFunction,
  34007. ribbonCloseArray: ribbonCloseArray,
  34008. ribbonClosePath: ribbonClosePath,
  34009. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34010. sideOrientation: sideOrientation,
  34011. instance: instance,
  34012. updatable: updatable
  34013. };
  34014. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34015. };
  34016. /**
  34017. * Creates lathe mesh.
  34018. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34019. * Please consider using the same method from the MeshBuilder class instead.
  34020. * 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
  34021. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  34022. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  34023. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  34024. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34025. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34026. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34027. */
  34028. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34029. var options = {
  34030. shape: shape,
  34031. radius: radius,
  34032. tessellation: tessellation,
  34033. sideOrientation: sideOrientation,
  34034. updatable: updatable
  34035. };
  34036. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34037. };
  34038. /**
  34039. * Creates a plane mesh.
  34040. * Please consider using the same method from the MeshBuilder class instead.
  34041. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  34042. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34043. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34044. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34045. */
  34046. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34047. var options = {
  34048. size: size,
  34049. width: size,
  34050. height: size,
  34051. sideOrientation: sideOrientation,
  34052. updatable: updatable
  34053. };
  34054. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34055. };
  34056. /**
  34057. * Creates a ground mesh.
  34058. * Please consider using the same method from the MeshBuilder class instead.
  34059. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  34060. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  34061. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34062. */
  34063. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34064. var options = {
  34065. width: width,
  34066. height: height,
  34067. subdivisions: subdivisions,
  34068. updatable: updatable
  34069. };
  34070. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34071. };
  34072. /**
  34073. * Creates a tiled ground mesh.
  34074. * Please consider using the same method from the MeshBuilder class instead.
  34075. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  34076. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  34077. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  34078. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  34079. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  34080. * numbers of subdivisions on the ground width and height of each tile.
  34081. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34082. */
  34083. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34084. var options = {
  34085. xmin: xmin,
  34086. zmin: zmin,
  34087. xmax: xmax,
  34088. zmax: zmax,
  34089. subdivisions: subdivisions,
  34090. precision: precision,
  34091. updatable: updatable
  34092. };
  34093. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34094. };
  34095. /**
  34096. * Creates a ground mesh from a height map.
  34097. * tuto : http://doc.babylonjs.com/babylon101/height_map
  34098. * Please consider using the same method from the MeshBuilder class instead.
  34099. * The parameter `url` sets the URL of the height map image resource.
  34100. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  34101. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  34102. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  34103. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  34104. * 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).
  34105. * This function is passed the newly built mesh :
  34106. * ```javascript
  34107. * function(mesh) { // do things
  34108. * return; }
  34109. * ```
  34110. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34111. */
  34112. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34113. var options = {
  34114. width: width,
  34115. height: height,
  34116. subdivisions: subdivisions,
  34117. minHeight: minHeight,
  34118. maxHeight: maxHeight,
  34119. updatable: updatable,
  34120. onReady: onReady
  34121. };
  34122. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34123. };
  34124. /**
  34125. * Creates a tube mesh.
  34126. * 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.
  34127. * Please consider using the same method from the MeshBuilder class instead.
  34128. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34129. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34130. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34131. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34132. * 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.
  34133. * It must return a radius value (positive float) :
  34134. * ```javascript
  34135. * var radiusFunction = function(i, distance) {
  34136. * // do things
  34137. * return radius; }
  34138. * ```
  34139. * 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
  34140. * 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
  34141. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34142. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34143. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34144. */
  34145. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34146. var options = {
  34147. path: path,
  34148. radius: radius,
  34149. tessellation: tessellation,
  34150. radiusFunction: radiusFunction,
  34151. arc: 1,
  34152. cap: cap,
  34153. updatable: updatable,
  34154. sideOrientation: sideOrientation,
  34155. instance: instance
  34156. };
  34157. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34158. };
  34159. /**
  34160. * Creates a polyhedron mesh.
  34161. * Please consider using the same method from the MeshBuilder class instead.
  34162. * 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
  34163. * to choose the wanted type.
  34164. * The parameter `size` (positive float, default 1) sets the polygon size.
  34165. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34166. * 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`.
  34167. * 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
  34168. * 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)`).
  34169. * 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
  34170. * 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.
  34171. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34172. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34173. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34174. */
  34175. Mesh.CreatePolyhedron = function (name, options, scene) {
  34176. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34177. };
  34178. /**
  34179. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34180. * Please consider using the same method from the MeshBuilder class instead.
  34181. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34182. * 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`).
  34183. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34184. * 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.
  34185. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34186. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34187. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34188. */
  34189. Mesh.CreateIcoSphere = function (name, options, scene) {
  34190. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34191. };
  34192. /**
  34193. * Creates a decal mesh.
  34194. * Please consider using the same method from the MeshBuilder class instead.
  34195. * 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.
  34196. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34197. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34198. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34199. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34200. */
  34201. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34202. var options = {
  34203. position: position,
  34204. normal: normal,
  34205. size: size,
  34206. angle: angle
  34207. };
  34208. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34209. };
  34210. // Skeletons
  34211. /**
  34212. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34213. */
  34214. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34215. if (!this._sourcePositions) {
  34216. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34217. if (!source) {
  34218. return this._sourcePositions;
  34219. }
  34220. this._sourcePositions = new Float32Array(source);
  34221. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34222. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34223. }
  34224. }
  34225. return this._sourcePositions;
  34226. };
  34227. /**
  34228. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34229. */
  34230. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34231. if (!this._sourceNormals) {
  34232. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34233. if (!source) {
  34234. return this._sourceNormals;
  34235. }
  34236. this._sourceNormals = new Float32Array(source);
  34237. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34238. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34239. }
  34240. }
  34241. return this._sourceNormals;
  34242. };
  34243. /**
  34244. * Updates the vertex buffer by applying transformation from the bones.
  34245. * Returns the Mesh.
  34246. *
  34247. * @param {skeleton} skeleton to apply
  34248. */
  34249. Mesh.prototype.applySkeleton = function (skeleton) {
  34250. if (!this.geometry) {
  34251. return this;
  34252. }
  34253. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34254. return this;
  34255. }
  34256. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34257. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34258. return this;
  34259. }
  34260. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34261. return this;
  34262. }
  34263. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34264. return this;
  34265. }
  34266. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34267. return this;
  34268. }
  34269. if (!this._sourcePositions) {
  34270. var submeshes = this.subMeshes.slice();
  34271. this.setPositionsForCPUSkinning();
  34272. this.subMeshes = submeshes;
  34273. }
  34274. if (!this._sourceNormals) {
  34275. this.setNormalsForCPUSkinning();
  34276. }
  34277. // positionsData checks for not being Float32Array will only pass at most once
  34278. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34279. if (!positionsData) {
  34280. return this;
  34281. }
  34282. if (!(positionsData instanceof Float32Array)) {
  34283. positionsData = new Float32Array(positionsData);
  34284. }
  34285. // normalsData checks for not being Float32Array will only pass at most once
  34286. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34287. if (!normalsData) {
  34288. return this;
  34289. }
  34290. if (!(normalsData instanceof Float32Array)) {
  34291. normalsData = new Float32Array(normalsData);
  34292. }
  34293. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34294. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34295. if (!matricesWeightsData || !matricesIndicesData) {
  34296. return this;
  34297. }
  34298. var needExtras = this.numBoneInfluencers > 4;
  34299. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34300. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34301. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34302. var tempVector3 = BABYLON.Vector3.Zero();
  34303. var finalMatrix = new BABYLON.Matrix();
  34304. var tempMatrix = new BABYLON.Matrix();
  34305. var matWeightIdx = 0;
  34306. var inf;
  34307. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34308. var weight;
  34309. for (inf = 0; inf < 4; inf++) {
  34310. weight = matricesWeightsData[matWeightIdx + inf];
  34311. if (weight > 0) {
  34312. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34313. finalMatrix.addToSelf(tempMatrix);
  34314. }
  34315. else
  34316. break;
  34317. }
  34318. if (needExtras) {
  34319. for (inf = 0; inf < 4; inf++) {
  34320. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34321. if (weight > 0) {
  34322. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34323. finalMatrix.addToSelf(tempMatrix);
  34324. }
  34325. else
  34326. break;
  34327. }
  34328. }
  34329. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34330. tempVector3.toArray(positionsData, index);
  34331. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34332. tempVector3.toArray(normalsData, index);
  34333. finalMatrix.reset();
  34334. }
  34335. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34336. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34337. return this;
  34338. };
  34339. // Tools
  34340. /**
  34341. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34342. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34343. */
  34344. Mesh.MinMax = function (meshes) {
  34345. var minVector = null;
  34346. var maxVector = null;
  34347. meshes.forEach(function (mesh, index, array) {
  34348. var boundingInfo = mesh.getBoundingInfo();
  34349. var boundingBox = boundingInfo.boundingBox;
  34350. if (!minVector || !maxVector) {
  34351. minVector = boundingBox.minimumWorld;
  34352. maxVector = boundingBox.maximumWorld;
  34353. }
  34354. else {
  34355. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34356. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34357. }
  34358. });
  34359. if (!minVector || !maxVector) {
  34360. return {
  34361. min: BABYLON.Vector3.Zero(),
  34362. max: BABYLON.Vector3.Zero()
  34363. };
  34364. }
  34365. return {
  34366. min: minVector,
  34367. max: maxVector
  34368. };
  34369. };
  34370. /**
  34371. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34372. */
  34373. Mesh.Center = function (meshesOrMinMaxVector) {
  34374. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34375. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34376. };
  34377. /**
  34378. * Merge the array of meshes into a single mesh for performance reasons.
  34379. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34380. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34381. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34382. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34383. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34384. */
  34385. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34386. if (disposeSource === void 0) { disposeSource = true; }
  34387. var index;
  34388. if (!allow32BitsIndices) {
  34389. var totalVertices = 0;
  34390. // Counting vertices
  34391. for (index = 0; index < meshes.length; index++) {
  34392. if (meshes[index]) {
  34393. totalVertices += meshes[index].getTotalVertices();
  34394. if (totalVertices > 65536) {
  34395. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34396. return null;
  34397. }
  34398. }
  34399. }
  34400. }
  34401. // Merge
  34402. var vertexData = null;
  34403. var otherVertexData;
  34404. var indiceArray = new Array();
  34405. var source = null;
  34406. for (index = 0; index < meshes.length; index++) {
  34407. if (meshes[index]) {
  34408. meshes[index].computeWorldMatrix(true);
  34409. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34410. otherVertexData.transform(meshes[index].getWorldMatrix());
  34411. if (vertexData) {
  34412. vertexData.merge(otherVertexData);
  34413. }
  34414. else {
  34415. vertexData = otherVertexData;
  34416. source = meshes[index];
  34417. }
  34418. if (subdivideWithSubMeshes) {
  34419. indiceArray.push(meshes[index].getTotalIndices());
  34420. }
  34421. }
  34422. }
  34423. source = source;
  34424. if (!meshSubclass) {
  34425. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34426. }
  34427. vertexData.applyToMesh(meshSubclass);
  34428. // Setting properties
  34429. meshSubclass.material = source.material;
  34430. meshSubclass.checkCollisions = source.checkCollisions;
  34431. // Cleaning
  34432. if (disposeSource) {
  34433. for (index = 0; index < meshes.length; index++) {
  34434. if (meshes[index]) {
  34435. meshes[index].dispose();
  34436. }
  34437. }
  34438. }
  34439. // Subdivide
  34440. if (subdivideWithSubMeshes) {
  34441. //-- removal of global submesh
  34442. meshSubclass.releaseSubMeshes();
  34443. index = 0;
  34444. var offset = 0;
  34445. //-- apply subdivision according to index table
  34446. while (index < indiceArray.length) {
  34447. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34448. offset += indiceArray[index];
  34449. index++;
  34450. }
  34451. }
  34452. return meshSubclass;
  34453. };
  34454. // Consts
  34455. Mesh._FRONTSIDE = 0;
  34456. Mesh._BACKSIDE = 1;
  34457. Mesh._DOUBLESIDE = 2;
  34458. Mesh._DEFAULTSIDE = 0;
  34459. Mesh._NO_CAP = 0;
  34460. Mesh._CAP_START = 1;
  34461. Mesh._CAP_END = 2;
  34462. Mesh._CAP_ALL = 3;
  34463. return Mesh;
  34464. }(BABYLON.AbstractMesh));
  34465. BABYLON.Mesh = Mesh;
  34466. })(BABYLON || (BABYLON = {}));
  34467. //# sourceMappingURL=babylon.mesh.js.map
  34468. var BABYLON;
  34469. (function (BABYLON) {
  34470. var BaseSubMesh = /** @class */ (function () {
  34471. function BaseSubMesh() {
  34472. }
  34473. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34474. get: function () {
  34475. return this._materialEffect;
  34476. },
  34477. enumerable: true,
  34478. configurable: true
  34479. });
  34480. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34481. if (defines === void 0) { defines = null; }
  34482. if (this._materialEffect === effect) {
  34483. if (!effect) {
  34484. this._materialDefines = null;
  34485. }
  34486. return;
  34487. }
  34488. this._materialDefines = defines;
  34489. this._materialEffect = effect;
  34490. };
  34491. return BaseSubMesh;
  34492. }());
  34493. BABYLON.BaseSubMesh = BaseSubMesh;
  34494. var SubMesh = /** @class */ (function (_super) {
  34495. __extends(SubMesh, _super);
  34496. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34497. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34498. var _this = _super.call(this) || this;
  34499. _this.materialIndex = materialIndex;
  34500. _this.verticesStart = verticesStart;
  34501. _this.verticesCount = verticesCount;
  34502. _this.indexStart = indexStart;
  34503. _this.indexCount = indexCount;
  34504. _this._renderId = 0;
  34505. _this._mesh = mesh;
  34506. _this._renderingMesh = renderingMesh || mesh;
  34507. mesh.subMeshes.push(_this);
  34508. _this._trianglePlanes = [];
  34509. _this._id = mesh.subMeshes.length - 1;
  34510. if (createBoundingBox) {
  34511. _this.refreshBoundingInfo();
  34512. mesh.computeWorldMatrix(true);
  34513. }
  34514. return _this;
  34515. }
  34516. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34517. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34518. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34519. };
  34520. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34521. get: function () {
  34522. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34523. },
  34524. enumerable: true,
  34525. configurable: true
  34526. });
  34527. /**
  34528. * Returns the submesh BoudingInfo object.
  34529. */
  34530. SubMesh.prototype.getBoundingInfo = function () {
  34531. if (this.IsGlobal) {
  34532. return this._mesh.getBoundingInfo();
  34533. }
  34534. return this._boundingInfo;
  34535. };
  34536. /**
  34537. * Sets the submesh BoundingInfo.
  34538. * Return the SubMesh.
  34539. */
  34540. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34541. this._boundingInfo = boundingInfo;
  34542. return this;
  34543. };
  34544. /**
  34545. * Returns the mesh of the current submesh.
  34546. */
  34547. SubMesh.prototype.getMesh = function () {
  34548. return this._mesh;
  34549. };
  34550. /**
  34551. * Returns the rendering mesh of the submesh.
  34552. */
  34553. SubMesh.prototype.getRenderingMesh = function () {
  34554. return this._renderingMesh;
  34555. };
  34556. /**
  34557. * Returns the submesh material.
  34558. */
  34559. SubMesh.prototype.getMaterial = function () {
  34560. var rootMaterial = this._renderingMesh.material;
  34561. if (rootMaterial === null || rootMaterial === undefined) {
  34562. return this._mesh.getScene().defaultMaterial;
  34563. }
  34564. else if (rootMaterial.getSubMaterial) {
  34565. var multiMaterial = rootMaterial;
  34566. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34567. if (this._currentMaterial !== effectiveMaterial) {
  34568. this._currentMaterial = effectiveMaterial;
  34569. this._materialDefines = null;
  34570. }
  34571. return effectiveMaterial;
  34572. }
  34573. return rootMaterial;
  34574. };
  34575. // Methods
  34576. /**
  34577. * Sets a new updated BoundingInfo object to the submesh.
  34578. * Returns the SubMesh.
  34579. */
  34580. SubMesh.prototype.refreshBoundingInfo = function () {
  34581. this._lastColliderWorldVertices = null;
  34582. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34583. return this;
  34584. }
  34585. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34586. if (!data) {
  34587. this._boundingInfo = this._mesh.getBoundingInfo();
  34588. return this;
  34589. }
  34590. var indices = this._renderingMesh.getIndices();
  34591. var extend;
  34592. //is this the only submesh?
  34593. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34594. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34595. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34596. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34597. }
  34598. else {
  34599. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34600. }
  34601. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34602. return this;
  34603. };
  34604. SubMesh.prototype._checkCollision = function (collider) {
  34605. var boundingInfo = this.getBoundingInfo();
  34606. return boundingInfo._checkCollision(collider);
  34607. };
  34608. /**
  34609. * Updates the submesh BoundingInfo.
  34610. * Returns the Submesh.
  34611. */
  34612. SubMesh.prototype.updateBoundingInfo = function (world) {
  34613. var boundingInfo = this.getBoundingInfo();
  34614. if (!boundingInfo) {
  34615. this.refreshBoundingInfo();
  34616. boundingInfo = this.getBoundingInfo();
  34617. }
  34618. boundingInfo.update(world);
  34619. return this;
  34620. };
  34621. /**
  34622. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34623. * Boolean returned.
  34624. */
  34625. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34626. var boundingInfo = this.getBoundingInfo();
  34627. if (!boundingInfo) {
  34628. return false;
  34629. }
  34630. return boundingInfo.isInFrustum(frustumPlanes);
  34631. };
  34632. /**
  34633. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34634. * Boolean returned.
  34635. */
  34636. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34637. var boundingInfo = this.getBoundingInfo();
  34638. if (!boundingInfo) {
  34639. return false;
  34640. }
  34641. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34642. };
  34643. /**
  34644. * Renders the submesh.
  34645. * Returns it.
  34646. */
  34647. SubMesh.prototype.render = function (enableAlphaMode) {
  34648. this._renderingMesh.render(this, enableAlphaMode);
  34649. return this;
  34650. };
  34651. /**
  34652. * Returns a new Index Buffer.
  34653. * Type returned : WebGLBuffer.
  34654. */
  34655. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34656. if (!this._linesIndexBuffer) {
  34657. var linesIndices = [];
  34658. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34659. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34660. }
  34661. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34662. this.linesIndexCount = linesIndices.length;
  34663. }
  34664. return this._linesIndexBuffer;
  34665. };
  34666. /**
  34667. * True is the passed Ray intersects the submesh bounding box.
  34668. * Boolean returned.
  34669. */
  34670. SubMesh.prototype.canIntersects = function (ray) {
  34671. var boundingInfo = this.getBoundingInfo();
  34672. if (!boundingInfo) {
  34673. return false;
  34674. }
  34675. return ray.intersectsBox(boundingInfo.boundingBox);
  34676. };
  34677. /**
  34678. * Returns an object IntersectionInfo.
  34679. */
  34680. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34681. var intersectInfo = null;
  34682. var material = this.getMaterial();
  34683. if (!material) {
  34684. return null;
  34685. }
  34686. switch (material.fillMode) {
  34687. case BABYLON.Material.PointListDrawMode:
  34688. case BABYLON.Material.LineListDrawMode:
  34689. case BABYLON.Material.LineLoopDrawMode:
  34690. case BABYLON.Material.LineStripDrawMode:
  34691. case BABYLON.Material.TriangleFanDrawMode:
  34692. case BABYLON.Material.TriangleStripDrawMode:
  34693. return null;
  34694. }
  34695. // LineMesh first as it's also a Mesh...
  34696. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34697. var lineMesh = this._mesh;
  34698. // Line test
  34699. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34700. var p0 = positions[indices[index]];
  34701. var p1 = positions[indices[index + 1]];
  34702. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34703. if (length < 0) {
  34704. continue;
  34705. }
  34706. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34707. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34708. if (fastCheck) {
  34709. break;
  34710. }
  34711. }
  34712. }
  34713. }
  34714. else {
  34715. // Triangles test
  34716. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34717. var p0 = positions[indices[index]];
  34718. var p1 = positions[indices[index + 1]];
  34719. var p2 = positions[indices[index + 2]];
  34720. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34721. if (currentIntersectInfo) {
  34722. if (currentIntersectInfo.distance < 0) {
  34723. continue;
  34724. }
  34725. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34726. intersectInfo = currentIntersectInfo;
  34727. intersectInfo.faceId = index / 3;
  34728. if (fastCheck) {
  34729. break;
  34730. }
  34731. }
  34732. }
  34733. }
  34734. }
  34735. return intersectInfo;
  34736. };
  34737. SubMesh.prototype._rebuild = function () {
  34738. if (this._linesIndexBuffer) {
  34739. this._linesIndexBuffer = null;
  34740. }
  34741. };
  34742. // Clone
  34743. /**
  34744. * Creates a new Submesh from the passed Mesh.
  34745. */
  34746. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34747. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34748. if (!this.IsGlobal) {
  34749. var boundingInfo = this.getBoundingInfo();
  34750. if (!boundingInfo) {
  34751. return result;
  34752. }
  34753. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34754. }
  34755. return result;
  34756. };
  34757. // Dispose
  34758. /**
  34759. * Disposes the Submesh.
  34760. * Returns nothing.
  34761. */
  34762. SubMesh.prototype.dispose = function () {
  34763. if (this._linesIndexBuffer) {
  34764. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34765. this._linesIndexBuffer = null;
  34766. }
  34767. // Remove from mesh
  34768. var index = this._mesh.subMeshes.indexOf(this);
  34769. this._mesh.subMeshes.splice(index, 1);
  34770. };
  34771. // Statics
  34772. /**
  34773. * Creates a new Submesh from the passed parameters :
  34774. * - materialIndex (integer) : the index of the main mesh material.
  34775. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34776. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34777. * - mesh (Mesh) : the main mesh to create the submesh from.
  34778. * - renderingMesh (optional Mesh) : rendering mesh.
  34779. */
  34780. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34781. var minVertexIndex = Number.MAX_VALUE;
  34782. var maxVertexIndex = -Number.MAX_VALUE;
  34783. renderingMesh = (renderingMesh || mesh);
  34784. var indices = renderingMesh.getIndices();
  34785. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34786. var vertexIndex = indices[index];
  34787. if (vertexIndex < minVertexIndex)
  34788. minVertexIndex = vertexIndex;
  34789. if (vertexIndex > maxVertexIndex)
  34790. maxVertexIndex = vertexIndex;
  34791. }
  34792. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34793. };
  34794. return SubMesh;
  34795. }(BaseSubMesh));
  34796. BABYLON.SubMesh = SubMesh;
  34797. })(BABYLON || (BABYLON = {}));
  34798. //# sourceMappingURL=babylon.subMesh.js.map
  34799. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34800. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34801. s = arguments[i];
  34802. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34803. t[p] = s[p];
  34804. }
  34805. return t;
  34806. };
  34807. var BABYLON;
  34808. (function (BABYLON) {
  34809. /**
  34810. * Manages the defines for the Material
  34811. */
  34812. var MaterialDefines = /** @class */ (function () {
  34813. function MaterialDefines() {
  34814. this._isDirty = true;
  34815. /** @hidden */
  34816. this._areLightsDirty = true;
  34817. /** @hidden */
  34818. this._areAttributesDirty = true;
  34819. /** @hidden */
  34820. this._areTexturesDirty = true;
  34821. /** @hidden */
  34822. this._areFresnelDirty = true;
  34823. /** @hidden */
  34824. this._areMiscDirty = true;
  34825. /** @hidden */
  34826. this._areImageProcessingDirty = true;
  34827. /** @hidden */
  34828. this._normals = false;
  34829. /** @hidden */
  34830. this._uvs = false;
  34831. /** @hidden */
  34832. this._needNormals = false;
  34833. /** @hidden */
  34834. this._needUVs = false;
  34835. }
  34836. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34837. /**
  34838. * Specifies if the material needs to be re-calculated
  34839. */
  34840. get: function () {
  34841. return this._isDirty;
  34842. },
  34843. enumerable: true,
  34844. configurable: true
  34845. });
  34846. /**
  34847. * Marks the material to indicate that it has been re-calculated
  34848. */
  34849. MaterialDefines.prototype.markAsProcessed = function () {
  34850. this._isDirty = false;
  34851. this._areAttributesDirty = false;
  34852. this._areTexturesDirty = false;
  34853. this._areFresnelDirty = false;
  34854. this._areLightsDirty = false;
  34855. this._areMiscDirty = false;
  34856. this._areImageProcessingDirty = false;
  34857. };
  34858. /**
  34859. * Marks the material to indicate that it needs to be re-calculated
  34860. */
  34861. MaterialDefines.prototype.markAsUnprocessed = function () {
  34862. this._isDirty = true;
  34863. };
  34864. /**
  34865. * Marks the material to indicate all of its defines need to be re-calculated
  34866. */
  34867. MaterialDefines.prototype.markAllAsDirty = function () {
  34868. this._areTexturesDirty = true;
  34869. this._areAttributesDirty = true;
  34870. this._areLightsDirty = true;
  34871. this._areFresnelDirty = true;
  34872. this._areMiscDirty = true;
  34873. this._areImageProcessingDirty = true;
  34874. this._isDirty = true;
  34875. };
  34876. /**
  34877. * Marks the material to indicate that image processing needs to be re-calculated
  34878. */
  34879. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34880. this._areImageProcessingDirty = true;
  34881. this._isDirty = true;
  34882. };
  34883. /**
  34884. * Marks the material to indicate the lights need to be re-calculated
  34885. */
  34886. MaterialDefines.prototype.markAsLightDirty = function () {
  34887. this._areLightsDirty = true;
  34888. this._isDirty = true;
  34889. };
  34890. /**
  34891. * Marks the attribute state as changed
  34892. */
  34893. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34894. this._areAttributesDirty = true;
  34895. this._isDirty = true;
  34896. };
  34897. /**
  34898. * Marks the texture state as changed
  34899. */
  34900. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34901. this._areTexturesDirty = true;
  34902. this._isDirty = true;
  34903. };
  34904. /**
  34905. * Marks the fresnel state as changed
  34906. */
  34907. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34908. this._areFresnelDirty = true;
  34909. this._isDirty = true;
  34910. };
  34911. /**
  34912. * Marks the misc state as changed
  34913. */
  34914. MaterialDefines.prototype.markAsMiscDirty = function () {
  34915. this._areMiscDirty = true;
  34916. this._isDirty = true;
  34917. };
  34918. /**
  34919. * Rebuilds the material defines
  34920. */
  34921. MaterialDefines.prototype.rebuild = function () {
  34922. if (this._keys) {
  34923. delete this._keys;
  34924. }
  34925. this._keys = [];
  34926. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34927. var key = _a[_i];
  34928. if (key[0] === "_") {
  34929. continue;
  34930. }
  34931. this._keys.push(key);
  34932. }
  34933. };
  34934. /**
  34935. * Specifies if two material defines are equal
  34936. * @param other - A material define instance to compare to
  34937. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34938. */
  34939. MaterialDefines.prototype.isEqual = function (other) {
  34940. if (this._keys.length !== other._keys.length) {
  34941. return false;
  34942. }
  34943. for (var index = 0; index < this._keys.length; index++) {
  34944. var prop = this._keys[index];
  34945. if (this[prop] !== other[prop]) {
  34946. return false;
  34947. }
  34948. }
  34949. return true;
  34950. };
  34951. /**
  34952. * Clones this instance's defines to another instance
  34953. * @param other - material defines to clone values to
  34954. */
  34955. MaterialDefines.prototype.cloneTo = function (other) {
  34956. if (this._keys.length !== other._keys.length) {
  34957. other._keys = this._keys.slice(0);
  34958. }
  34959. for (var index = 0; index < this._keys.length; index++) {
  34960. var prop = this._keys[index];
  34961. other[prop] = this[prop];
  34962. }
  34963. };
  34964. /**
  34965. * Resets the material define values
  34966. */
  34967. MaterialDefines.prototype.reset = function () {
  34968. for (var index = 0; index < this._keys.length; index++) {
  34969. var prop = this._keys[index];
  34970. var type = typeof this[prop];
  34971. switch (type) {
  34972. case "number":
  34973. this[prop] = 0;
  34974. break;
  34975. case "string":
  34976. this[prop] = "";
  34977. break;
  34978. default:
  34979. this[prop] = false;
  34980. break;
  34981. }
  34982. }
  34983. };
  34984. /**
  34985. * Converts the material define values to a string
  34986. * @returns - String of material define information
  34987. */
  34988. MaterialDefines.prototype.toString = function () {
  34989. var result = "";
  34990. for (var index = 0; index < this._keys.length; index++) {
  34991. var prop = this._keys[index];
  34992. var value = this[prop];
  34993. var type = typeof value;
  34994. switch (type) {
  34995. case "number":
  34996. case "string":
  34997. result += "#define " + prop + " " + value + "\n";
  34998. break;
  34999. default:
  35000. if (value) {
  35001. result += "#define " + prop + "\n";
  35002. }
  35003. break;
  35004. }
  35005. }
  35006. return result;
  35007. };
  35008. return MaterialDefines;
  35009. }());
  35010. BABYLON.MaterialDefines = MaterialDefines;
  35011. /**
  35012. * Base class for the main features of a material in Babylon.js
  35013. */
  35014. var Material = /** @class */ (function () {
  35015. /**
  35016. * Creates a material instance
  35017. * @param name defines the name of the material
  35018. * @param scene defines the scene to reference
  35019. * @param doNotAdd specifies if the material should be added to the scene
  35020. */
  35021. function Material(name, scene, doNotAdd) {
  35022. /**
  35023. * Specifies if the ready state should be checked on each call
  35024. */
  35025. this.checkReadyOnEveryCall = false;
  35026. /**
  35027. * Specifies if the ready state should be checked once
  35028. */
  35029. this.checkReadyOnlyOnce = false;
  35030. /**
  35031. * The state of the material
  35032. */
  35033. this.state = "";
  35034. /**
  35035. * The alpha value of the material
  35036. */
  35037. this._alpha = 1.0;
  35038. /**
  35039. * Specifies if back face culling is enabled
  35040. */
  35041. this._backFaceCulling = true;
  35042. /**
  35043. * Specifies if the material should be serialized
  35044. */
  35045. this.doNotSerialize = false;
  35046. /**
  35047. * Specifies if the effect should be stored on sub meshes
  35048. */
  35049. this.storeEffectOnSubMeshes = false;
  35050. /**
  35051. * An event triggered when the material is disposed
  35052. */
  35053. this.onDisposeObservable = new BABYLON.Observable();
  35054. /**
  35055. * An event triggered when the material is bound
  35056. */
  35057. this.onBindObservable = new BABYLON.Observable();
  35058. /**
  35059. * An event triggered when the material is unbound
  35060. */
  35061. this.onUnBindObservable = new BABYLON.Observable();
  35062. /**
  35063. * Stores the value of the alpha mode
  35064. */
  35065. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35066. /**
  35067. * Stores the state of the need depth pre-pass value
  35068. */
  35069. this._needDepthPrePass = false;
  35070. /**
  35071. * Specifies if depth writing should be disabled
  35072. */
  35073. this.disableDepthWrite = false;
  35074. /**
  35075. * Specifies if depth writing should be forced
  35076. */
  35077. this.forceDepthWrite = false;
  35078. /**
  35079. * Specifies if there should be a separate pass for culling
  35080. */
  35081. this.separateCullingPass = false;
  35082. /**
  35083. * Stores the state specifing if fog should be enabled
  35084. */
  35085. this._fogEnabled = true;
  35086. /**
  35087. * Stores the size of points
  35088. */
  35089. this.pointSize = 1.0;
  35090. /**
  35091. * Stores the z offset value
  35092. */
  35093. this.zOffset = 0;
  35094. /**
  35095. * Specifies if the material was previously ready
  35096. */
  35097. this._wasPreviouslyReady = false;
  35098. /**
  35099. * Stores the fill mode state
  35100. */
  35101. this._fillMode = Material.TriangleFillMode;
  35102. this.name = name;
  35103. this.id = name || BABYLON.Tools.RandomId();
  35104. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35105. this.uniqueId = this._scene.getUniqueId();
  35106. if (this._scene.useRightHandedSystem) {
  35107. this.sideOrientation = Material.ClockWiseSideOrientation;
  35108. }
  35109. else {
  35110. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35111. }
  35112. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35113. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35114. if (!doNotAdd) {
  35115. this._scene.materials.push(this);
  35116. }
  35117. }
  35118. Object.defineProperty(Material, "TriangleFillMode", {
  35119. /**
  35120. * Returns the triangle fill mode
  35121. */
  35122. get: function () {
  35123. return Material._TriangleFillMode;
  35124. },
  35125. enumerable: true,
  35126. configurable: true
  35127. });
  35128. Object.defineProperty(Material, "WireFrameFillMode", {
  35129. /**
  35130. * Returns the wireframe mode
  35131. */
  35132. get: function () {
  35133. return Material._WireFrameFillMode;
  35134. },
  35135. enumerable: true,
  35136. configurable: true
  35137. });
  35138. Object.defineProperty(Material, "PointFillMode", {
  35139. /**
  35140. * Returns the point fill mode
  35141. */
  35142. get: function () {
  35143. return Material._PointFillMode;
  35144. },
  35145. enumerable: true,
  35146. configurable: true
  35147. });
  35148. Object.defineProperty(Material, "PointListDrawMode", {
  35149. /**
  35150. * Returns the point list draw mode
  35151. */
  35152. get: function () {
  35153. return Material._PointListDrawMode;
  35154. },
  35155. enumerable: true,
  35156. configurable: true
  35157. });
  35158. Object.defineProperty(Material, "LineListDrawMode", {
  35159. /**
  35160. * Returns the line list draw mode
  35161. */
  35162. get: function () {
  35163. return Material._LineListDrawMode;
  35164. },
  35165. enumerable: true,
  35166. configurable: true
  35167. });
  35168. Object.defineProperty(Material, "LineLoopDrawMode", {
  35169. /**
  35170. * Returns the line loop draw mode
  35171. */
  35172. get: function () {
  35173. return Material._LineLoopDrawMode;
  35174. },
  35175. enumerable: true,
  35176. configurable: true
  35177. });
  35178. Object.defineProperty(Material, "LineStripDrawMode", {
  35179. /**
  35180. * Returns the line strip draw mode
  35181. */
  35182. get: function () {
  35183. return Material._LineStripDrawMode;
  35184. },
  35185. enumerable: true,
  35186. configurable: true
  35187. });
  35188. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35189. /**
  35190. * Returns the triangle strip draw mode
  35191. */
  35192. get: function () {
  35193. return Material._TriangleStripDrawMode;
  35194. },
  35195. enumerable: true,
  35196. configurable: true
  35197. });
  35198. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35199. /**
  35200. * Returns the triangle fan draw mode
  35201. */
  35202. get: function () {
  35203. return Material._TriangleFanDrawMode;
  35204. },
  35205. enumerable: true,
  35206. configurable: true
  35207. });
  35208. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35209. /**
  35210. * Returns the clock-wise side orientation
  35211. */
  35212. get: function () {
  35213. return Material._ClockWiseSideOrientation;
  35214. },
  35215. enumerable: true,
  35216. configurable: true
  35217. });
  35218. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35219. /**
  35220. * Returns the counter clock-wise side orientation
  35221. */
  35222. get: function () {
  35223. return Material._CounterClockWiseSideOrientation;
  35224. },
  35225. enumerable: true,
  35226. configurable: true
  35227. });
  35228. Object.defineProperty(Material, "TextureDirtyFlag", {
  35229. /**
  35230. * Returns the dirty texture flag value
  35231. */
  35232. get: function () {
  35233. return Material._TextureDirtyFlag;
  35234. },
  35235. enumerable: true,
  35236. configurable: true
  35237. });
  35238. Object.defineProperty(Material, "LightDirtyFlag", {
  35239. /**
  35240. * Returns the dirty light flag value
  35241. */
  35242. get: function () {
  35243. return Material._LightDirtyFlag;
  35244. },
  35245. enumerable: true,
  35246. configurable: true
  35247. });
  35248. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35249. /**
  35250. * Returns the dirty fresnel flag value
  35251. */
  35252. get: function () {
  35253. return Material._FresnelDirtyFlag;
  35254. },
  35255. enumerable: true,
  35256. configurable: true
  35257. });
  35258. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35259. /**
  35260. * Returns the dirty attributes flag value
  35261. */
  35262. get: function () {
  35263. return Material._AttributesDirtyFlag;
  35264. },
  35265. enumerable: true,
  35266. configurable: true
  35267. });
  35268. Object.defineProperty(Material, "MiscDirtyFlag", {
  35269. /**
  35270. * Returns the dirty misc flag value
  35271. */
  35272. get: function () {
  35273. return Material._MiscDirtyFlag;
  35274. },
  35275. enumerable: true,
  35276. configurable: true
  35277. });
  35278. Object.defineProperty(Material.prototype, "alpha", {
  35279. /**
  35280. * Gets the alpha value of the material
  35281. */
  35282. get: function () {
  35283. return this._alpha;
  35284. },
  35285. /**
  35286. * Sets the alpha value of the material
  35287. */
  35288. set: function (value) {
  35289. if (this._alpha === value) {
  35290. return;
  35291. }
  35292. this._alpha = value;
  35293. this.markAsDirty(Material.MiscDirtyFlag);
  35294. },
  35295. enumerable: true,
  35296. configurable: true
  35297. });
  35298. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35299. /**
  35300. * Gets the back-face culling state
  35301. */
  35302. get: function () {
  35303. return this._backFaceCulling;
  35304. },
  35305. /**
  35306. * Sets the back-face culling state
  35307. */
  35308. set: function (value) {
  35309. if (this._backFaceCulling === value) {
  35310. return;
  35311. }
  35312. this._backFaceCulling = value;
  35313. this.markAsDirty(Material.TextureDirtyFlag);
  35314. },
  35315. enumerable: true,
  35316. configurable: true
  35317. });
  35318. Object.defineProperty(Material.prototype, "onDispose", {
  35319. /**
  35320. * Called during a dispose event
  35321. */
  35322. set: function (callback) {
  35323. if (this._onDisposeObserver) {
  35324. this.onDisposeObservable.remove(this._onDisposeObserver);
  35325. }
  35326. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35327. },
  35328. enumerable: true,
  35329. configurable: true
  35330. });
  35331. Object.defineProperty(Material.prototype, "onBind", {
  35332. /**
  35333. * Called during a bind event
  35334. */
  35335. set: function (callback) {
  35336. if (this._onBindObserver) {
  35337. this.onBindObservable.remove(this._onBindObserver);
  35338. }
  35339. this._onBindObserver = this.onBindObservable.add(callback);
  35340. },
  35341. enumerable: true,
  35342. configurable: true
  35343. });
  35344. Object.defineProperty(Material.prototype, "alphaMode", {
  35345. /**
  35346. * Gets the value of the alpha mode
  35347. */
  35348. get: function () {
  35349. return this._alphaMode;
  35350. },
  35351. /**
  35352. * Sets the value of the alpha mode.
  35353. *
  35354. * | Value | Type | Description |
  35355. * | --- | --- | --- |
  35356. * | 0 | ALPHA_DISABLE | |
  35357. * | 1 | ALPHA_ADD | |
  35358. * | 2 | ALPHA_COMBINE | |
  35359. * | 3 | ALPHA_SUBTRACT | |
  35360. * | 4 | ALPHA_MULTIPLY | |
  35361. * | 5 | ALPHA_MAXIMIZED | |
  35362. * | 6 | ALPHA_ONEONE | |
  35363. * | 7 | ALPHA_PREMULTIPLIED | |
  35364. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35365. * | 9 | ALPHA_INTERPOLATE | |
  35366. * | 10 | ALPHA_SCREENMODE | |
  35367. *
  35368. */
  35369. set: function (value) {
  35370. if (this._alphaMode === value) {
  35371. return;
  35372. }
  35373. this._alphaMode = value;
  35374. this.markAsDirty(Material.TextureDirtyFlag);
  35375. },
  35376. enumerable: true,
  35377. configurable: true
  35378. });
  35379. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35380. /**
  35381. * Gets the depth pre-pass value
  35382. */
  35383. get: function () {
  35384. return this._needDepthPrePass;
  35385. },
  35386. /**
  35387. * Sets the need depth pre-pass value
  35388. */
  35389. set: function (value) {
  35390. if (this._needDepthPrePass === value) {
  35391. return;
  35392. }
  35393. this._needDepthPrePass = value;
  35394. if (this._needDepthPrePass) {
  35395. this.checkReadyOnEveryCall = true;
  35396. }
  35397. },
  35398. enumerable: true,
  35399. configurable: true
  35400. });
  35401. Object.defineProperty(Material.prototype, "fogEnabled", {
  35402. /**
  35403. * Gets the value of the fog enabled state
  35404. */
  35405. get: function () {
  35406. return this._fogEnabled;
  35407. },
  35408. /**
  35409. * Sets the state for enabling fog
  35410. */
  35411. set: function (value) {
  35412. if (this._fogEnabled === value) {
  35413. return;
  35414. }
  35415. this._fogEnabled = value;
  35416. this.markAsDirty(Material.MiscDirtyFlag);
  35417. },
  35418. enumerable: true,
  35419. configurable: true
  35420. });
  35421. Object.defineProperty(Material.prototype, "wireframe", {
  35422. /**
  35423. * Gets a value specifying if wireframe mode is enabled
  35424. */
  35425. get: function () {
  35426. switch (this._fillMode) {
  35427. case Material.WireFrameFillMode:
  35428. case Material.LineListDrawMode:
  35429. case Material.LineLoopDrawMode:
  35430. case Material.LineStripDrawMode:
  35431. return true;
  35432. }
  35433. return this._scene.forceWireframe;
  35434. },
  35435. /**
  35436. * Sets the state of wireframe mode
  35437. */
  35438. set: function (value) {
  35439. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35440. },
  35441. enumerable: true,
  35442. configurable: true
  35443. });
  35444. Object.defineProperty(Material.prototype, "pointsCloud", {
  35445. /**
  35446. * Gets the value specifying if point clouds are enabled
  35447. */
  35448. get: function () {
  35449. switch (this._fillMode) {
  35450. case Material.PointFillMode:
  35451. case Material.PointListDrawMode:
  35452. return true;
  35453. }
  35454. return this._scene.forcePointsCloud;
  35455. },
  35456. /**
  35457. * Sets the state of point cloud mode
  35458. */
  35459. set: function (value) {
  35460. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35461. },
  35462. enumerable: true,
  35463. configurable: true
  35464. });
  35465. Object.defineProperty(Material.prototype, "fillMode", {
  35466. /**
  35467. * Gets the material fill mode
  35468. */
  35469. get: function () {
  35470. return this._fillMode;
  35471. },
  35472. /**
  35473. * Sets the material fill mode
  35474. */
  35475. set: function (value) {
  35476. if (this._fillMode === value) {
  35477. return;
  35478. }
  35479. this._fillMode = value;
  35480. this.markAsDirty(Material.MiscDirtyFlag);
  35481. },
  35482. enumerable: true,
  35483. configurable: true
  35484. });
  35485. /**
  35486. * Returns a string representation of the current material
  35487. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35488. * @returns a string with material information
  35489. */
  35490. Material.prototype.toString = function (fullDetails) {
  35491. var ret = "Name: " + this.name;
  35492. if (fullDetails) {
  35493. }
  35494. return ret;
  35495. };
  35496. /**
  35497. * Gets the class name of the material
  35498. * @returns a string with the class name of the material
  35499. */
  35500. Material.prototype.getClassName = function () {
  35501. return "Material";
  35502. };
  35503. Object.defineProperty(Material.prototype, "isFrozen", {
  35504. /**
  35505. * Specifies if updates for the material been locked
  35506. */
  35507. get: function () {
  35508. return this.checkReadyOnlyOnce;
  35509. },
  35510. enumerable: true,
  35511. configurable: true
  35512. });
  35513. /**
  35514. * Locks updates for the material
  35515. */
  35516. Material.prototype.freeze = function () {
  35517. this.checkReadyOnlyOnce = true;
  35518. };
  35519. /**
  35520. * Unlocks updates for the material
  35521. */
  35522. Material.prototype.unfreeze = function () {
  35523. this.checkReadyOnlyOnce = false;
  35524. };
  35525. /**
  35526. * Specifies if the material is ready to be used
  35527. * @param mesh defines the mesh to check
  35528. * @param useInstances specifies if instances should be used
  35529. * @returns a boolean indicating if the material is ready to be used
  35530. */
  35531. Material.prototype.isReady = function (mesh, useInstances) {
  35532. return true;
  35533. };
  35534. /**
  35535. * Specifies that the submesh is ready to be used
  35536. * @param mesh defines the mesh to check
  35537. * @param subMesh defines which submesh to check
  35538. * @param useInstances specifies that instances should be used
  35539. * @returns a boolean indicating that the submesh is ready or not
  35540. */
  35541. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35542. return false;
  35543. };
  35544. /**
  35545. * Returns the material effect
  35546. * @returns the effect associated with the material
  35547. */
  35548. Material.prototype.getEffect = function () {
  35549. return this._effect;
  35550. };
  35551. /**
  35552. * Returns the current scene
  35553. * @returns a Scene
  35554. */
  35555. Material.prototype.getScene = function () {
  35556. return this._scene;
  35557. };
  35558. /**
  35559. * Specifies if the material will require alpha blending
  35560. * @returns a boolean specifying if alpha blending is needed
  35561. */
  35562. Material.prototype.needAlphaBlending = function () {
  35563. return (this.alpha < 1.0);
  35564. };
  35565. /**
  35566. * Specifies if the mesh will require alpha blending
  35567. * @param mesh defines the mesh to check
  35568. * @returns a boolean specifying if alpha blending is needed for the mesh
  35569. */
  35570. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35571. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35572. };
  35573. /**
  35574. * Specifies if this material should be rendered in alpha test mode
  35575. * @returns a boolean specifying if an alpha test is needed.
  35576. */
  35577. Material.prototype.needAlphaTesting = function () {
  35578. return false;
  35579. };
  35580. /**
  35581. * Gets the texture used for the alpha test
  35582. * @returns the texture to use for alpha testing
  35583. */
  35584. Material.prototype.getAlphaTestTexture = function () {
  35585. return null;
  35586. };
  35587. /**
  35588. * Marks the material to indicate that it needs to be re-calculated
  35589. */
  35590. Material.prototype.markDirty = function () {
  35591. this._wasPreviouslyReady = false;
  35592. };
  35593. /** @hidden */
  35594. Material.prototype._preBind = function (effect, overrideOrientation) {
  35595. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35596. var engine = this._scene.getEngine();
  35597. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35598. var reverse = orientation === Material.ClockWiseSideOrientation;
  35599. engine.enableEffect(effect ? effect : this._effect);
  35600. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35601. return reverse;
  35602. };
  35603. /**
  35604. * Binds the material to the mesh
  35605. * @param world defines the world transformation matrix
  35606. * @param mesh defines the mesh to bind the material to
  35607. */
  35608. Material.prototype.bind = function (world, mesh) {
  35609. };
  35610. /**
  35611. * Binds the submesh to the material
  35612. * @param world defines the world transformation matrix
  35613. * @param mesh defines the mesh containing the submesh
  35614. * @param subMesh defines the submesh to bind the material to
  35615. */
  35616. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35617. };
  35618. /**
  35619. * Binds the world matrix to the material
  35620. * @param world defines the world transformation matrix
  35621. */
  35622. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35623. };
  35624. /**
  35625. * Binds the scene's uniform buffer to the effect.
  35626. * @param effect defines the effect to bind to the scene uniform buffer
  35627. * @param sceneUbo defines the uniform buffer storing scene data
  35628. */
  35629. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35630. sceneUbo.bindToEffect(effect, "Scene");
  35631. };
  35632. /**
  35633. * Binds the view matrix to the effect
  35634. * @param effect defines the effect to bind the view matrix to
  35635. */
  35636. Material.prototype.bindView = function (effect) {
  35637. if (!this._useUBO) {
  35638. effect.setMatrix("view", this.getScene().getViewMatrix());
  35639. }
  35640. else {
  35641. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35642. }
  35643. };
  35644. /**
  35645. * Binds the view projection matrix to the effect
  35646. * @param effect defines the effect to bind the view projection matrix to
  35647. */
  35648. Material.prototype.bindViewProjection = function (effect) {
  35649. if (!this._useUBO) {
  35650. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35651. }
  35652. else {
  35653. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35654. }
  35655. };
  35656. /**
  35657. * Specifies if material alpha testing should be turned on for the mesh
  35658. * @param mesh defines the mesh to check
  35659. */
  35660. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35661. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35662. };
  35663. /**
  35664. * Processes to execute after binding the material to a mesh
  35665. * @param mesh defines the rendered mesh
  35666. */
  35667. Material.prototype._afterBind = function (mesh) {
  35668. this._scene._cachedMaterial = this;
  35669. if (mesh) {
  35670. this._scene._cachedVisibility = mesh.visibility;
  35671. }
  35672. else {
  35673. this._scene._cachedVisibility = 1;
  35674. }
  35675. if (mesh) {
  35676. this.onBindObservable.notifyObservers(mesh);
  35677. }
  35678. if (this.disableDepthWrite) {
  35679. var engine = this._scene.getEngine();
  35680. this._cachedDepthWriteState = engine.getDepthWrite();
  35681. engine.setDepthWrite(false);
  35682. }
  35683. };
  35684. /**
  35685. * Unbinds the material from the mesh
  35686. */
  35687. Material.prototype.unbind = function () {
  35688. this.onUnBindObservable.notifyObservers(this);
  35689. if (this.disableDepthWrite) {
  35690. var engine = this._scene.getEngine();
  35691. engine.setDepthWrite(this._cachedDepthWriteState);
  35692. }
  35693. };
  35694. /**
  35695. * Gets the active textures from the material
  35696. * @returns an array of textures
  35697. */
  35698. Material.prototype.getActiveTextures = function () {
  35699. return [];
  35700. };
  35701. /**
  35702. * Specifies if the material uses a texture
  35703. * @param texture defines the texture to check against the material
  35704. * @returns a boolean specifying if the material uses the texture
  35705. */
  35706. Material.prototype.hasTexture = function (texture) {
  35707. return false;
  35708. };
  35709. /**
  35710. * Makes a duplicate of the material, and gives it a new name
  35711. * @param name defines the new name for the duplicated material
  35712. * @returns the cloned material
  35713. */
  35714. Material.prototype.clone = function (name) {
  35715. return null;
  35716. };
  35717. /**
  35718. * Gets the meshes bound to the material
  35719. * @returns an array of meshes bound to the material
  35720. */
  35721. Material.prototype.getBindedMeshes = function () {
  35722. var result = new Array();
  35723. for (var index = 0; index < this._scene.meshes.length; index++) {
  35724. var mesh = this._scene.meshes[index];
  35725. if (mesh.material === this) {
  35726. result.push(mesh);
  35727. }
  35728. }
  35729. return result;
  35730. };
  35731. /**
  35732. * Force shader compilation
  35733. * @param mesh defines the mesh associated with this material
  35734. * @param onCompiled defines a function to execute once the material is compiled
  35735. * @param options defines the options to configure the compilation
  35736. */
  35737. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35738. var _this = this;
  35739. var localOptions = __assign({ clipPlane: false }, options);
  35740. var subMesh = new BABYLON.BaseSubMesh();
  35741. var scene = this.getScene();
  35742. var checkReady = function () {
  35743. if (!_this._scene || !_this._scene.getEngine()) {
  35744. return;
  35745. }
  35746. if (subMesh._materialDefines) {
  35747. subMesh._materialDefines._renderId = -1;
  35748. }
  35749. var clipPlaneState = scene.clipPlane;
  35750. if (localOptions.clipPlane) {
  35751. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35752. }
  35753. if (_this.storeEffectOnSubMeshes) {
  35754. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35755. if (onCompiled) {
  35756. onCompiled(_this);
  35757. }
  35758. }
  35759. else {
  35760. setTimeout(checkReady, 16);
  35761. }
  35762. }
  35763. else {
  35764. if (_this.isReady(mesh)) {
  35765. if (onCompiled) {
  35766. onCompiled(_this);
  35767. }
  35768. }
  35769. else {
  35770. setTimeout(checkReady, 16);
  35771. }
  35772. }
  35773. if (localOptions.clipPlane) {
  35774. scene.clipPlane = clipPlaneState;
  35775. }
  35776. };
  35777. checkReady();
  35778. };
  35779. /**
  35780. * Force shader compilation
  35781. * @param mesh defines the mesh that will use this material
  35782. * @param options defines additional options for compiling the shaders
  35783. * @returns a promise that resolves when the compilation completes
  35784. */
  35785. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35786. var _this = this;
  35787. return new Promise(function (resolve) {
  35788. _this.forceCompilation(mesh, function () {
  35789. resolve();
  35790. }, options);
  35791. });
  35792. };
  35793. /**
  35794. * Marks a define in the material to indicate that it needs to be re-computed
  35795. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35796. */
  35797. Material.prototype.markAsDirty = function (flag) {
  35798. if (flag & Material.TextureDirtyFlag) {
  35799. this._markAllSubMeshesAsTexturesDirty();
  35800. }
  35801. if (flag & Material.LightDirtyFlag) {
  35802. this._markAllSubMeshesAsLightsDirty();
  35803. }
  35804. if (flag & Material.FresnelDirtyFlag) {
  35805. this._markAllSubMeshesAsFresnelDirty();
  35806. }
  35807. if (flag & Material.AttributesDirtyFlag) {
  35808. this._markAllSubMeshesAsAttributesDirty();
  35809. }
  35810. if (flag & Material.MiscDirtyFlag) {
  35811. this._markAllSubMeshesAsMiscDirty();
  35812. }
  35813. this.getScene().resetCachedMaterial();
  35814. };
  35815. /**
  35816. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35817. * @param func defines a function which checks material defines against the submeshes
  35818. */
  35819. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35820. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35821. var mesh = _a[_i];
  35822. if (!mesh.subMeshes) {
  35823. continue;
  35824. }
  35825. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35826. var subMesh = _c[_b];
  35827. if (subMesh.getMaterial() !== this) {
  35828. continue;
  35829. }
  35830. if (!subMesh._materialDefines) {
  35831. continue;
  35832. }
  35833. func(subMesh._materialDefines);
  35834. }
  35835. }
  35836. };
  35837. /**
  35838. * Indicates that image processing needs to be re-calculated for all submeshes
  35839. */
  35840. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35841. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35842. };
  35843. /**
  35844. * Indicates that textures need to be re-calculated for all submeshes
  35845. */
  35846. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35847. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35848. };
  35849. /**
  35850. * Indicates that fresnel needs to be re-calculated for all submeshes
  35851. */
  35852. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35853. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35854. };
  35855. /**
  35856. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35857. */
  35858. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35859. this._markAllSubMeshesAsDirty(function (defines) {
  35860. defines.markAsFresnelDirty();
  35861. defines.markAsMiscDirty();
  35862. });
  35863. };
  35864. /**
  35865. * Indicates that lights need to be re-calculated for all submeshes
  35866. */
  35867. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35868. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35869. };
  35870. /**
  35871. * Indicates that attributes need to be re-calculated for all submeshes
  35872. */
  35873. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35874. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35875. };
  35876. /**
  35877. * Indicates that misc needs to be re-calculated for all submeshes
  35878. */
  35879. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35880. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35881. };
  35882. /**
  35883. * Indicates that textures and misc need to be re-calculated for all submeshes
  35884. */
  35885. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35886. this._markAllSubMeshesAsDirty(function (defines) {
  35887. defines.markAsTexturesDirty();
  35888. defines.markAsMiscDirty();
  35889. });
  35890. };
  35891. /**
  35892. * Disposes the material
  35893. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35894. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35895. */
  35896. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35897. // Animations
  35898. this.getScene().stopAnimation(this);
  35899. this.getScene().freeProcessedMaterials();
  35900. // Remove from scene
  35901. var index = this._scene.materials.indexOf(this);
  35902. if (index >= 0) {
  35903. this._scene.materials.splice(index, 1);
  35904. }
  35905. // Remove from meshes
  35906. for (index = 0; index < this._scene.meshes.length; index++) {
  35907. var mesh = this._scene.meshes[index];
  35908. if (mesh.material === this) {
  35909. mesh.material = null;
  35910. if (mesh.geometry) {
  35911. var geometry = (mesh.geometry);
  35912. if (this.storeEffectOnSubMeshes) {
  35913. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35914. var subMesh = _a[_i];
  35915. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35916. if (forceDisposeEffect && subMesh._materialEffect) {
  35917. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35918. }
  35919. }
  35920. }
  35921. else {
  35922. geometry._releaseVertexArrayObject(this._effect);
  35923. }
  35924. }
  35925. }
  35926. }
  35927. this._uniformBuffer.dispose();
  35928. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35929. if (forceDisposeEffect && this._effect) {
  35930. if (!this.storeEffectOnSubMeshes) {
  35931. this._scene.getEngine()._releaseEffect(this._effect);
  35932. }
  35933. this._effect = null;
  35934. }
  35935. // Callback
  35936. this.onDisposeObservable.notifyObservers(this);
  35937. this.onDisposeObservable.clear();
  35938. this.onBindObservable.clear();
  35939. this.onUnBindObservable.clear();
  35940. };
  35941. /**
  35942. * Serializes this material
  35943. * @returns the serialized material object
  35944. */
  35945. Material.prototype.serialize = function () {
  35946. return BABYLON.SerializationHelper.Serialize(this);
  35947. };
  35948. /**
  35949. * Creates a MultiMaterial from parsed MultiMaterial data.
  35950. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35951. * @param scene defines the hosting scene
  35952. * @returns a new MultiMaterial
  35953. */
  35954. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35955. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35956. multiMaterial.id = parsedMultiMaterial.id;
  35957. if (BABYLON.Tags) {
  35958. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35959. }
  35960. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35961. var subMatId = parsedMultiMaterial.materials[matIndex];
  35962. if (subMatId) {
  35963. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35964. }
  35965. else {
  35966. multiMaterial.subMaterials.push(null);
  35967. }
  35968. }
  35969. return multiMaterial;
  35970. };
  35971. /**
  35972. * Creates a material from parsed material data
  35973. * @param parsedMaterial defines parsed material data
  35974. * @param scene defines the hosting scene
  35975. * @param rootUrl defines the root URL to use to load textures
  35976. * @returns a new material
  35977. */
  35978. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35979. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35980. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35981. }
  35982. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35983. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35984. if (!BABYLON.LegacyPBRMaterial) {
  35985. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35986. return;
  35987. }
  35988. }
  35989. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35990. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35991. };
  35992. // Triangle views
  35993. Material._TriangleFillMode = 0;
  35994. Material._WireFrameFillMode = 1;
  35995. Material._PointFillMode = 2;
  35996. // Draw modes
  35997. Material._PointListDrawMode = 3;
  35998. Material._LineListDrawMode = 4;
  35999. Material._LineLoopDrawMode = 5;
  36000. Material._LineStripDrawMode = 6;
  36001. Material._TriangleStripDrawMode = 7;
  36002. Material._TriangleFanDrawMode = 8;
  36003. /**
  36004. * Stores the clock-wise side orientation
  36005. */
  36006. Material._ClockWiseSideOrientation = 0;
  36007. /**
  36008. * Stores the counter clock-wise side orientation
  36009. */
  36010. Material._CounterClockWiseSideOrientation = 1;
  36011. /**
  36012. * The dirty texture flag value
  36013. */
  36014. Material._TextureDirtyFlag = 1;
  36015. /**
  36016. * The dirty light flag value
  36017. */
  36018. Material._LightDirtyFlag = 2;
  36019. /**
  36020. * The dirty fresnel flag value
  36021. */
  36022. Material._FresnelDirtyFlag = 4;
  36023. /**
  36024. * The dirty attribute flag value
  36025. */
  36026. Material._AttributesDirtyFlag = 8;
  36027. /**
  36028. * The dirty misc flag value
  36029. */
  36030. Material._MiscDirtyFlag = 16;
  36031. __decorate([
  36032. BABYLON.serialize()
  36033. ], Material.prototype, "id", void 0);
  36034. __decorate([
  36035. BABYLON.serialize()
  36036. ], Material.prototype, "uniqueId", void 0);
  36037. __decorate([
  36038. BABYLON.serialize()
  36039. ], Material.prototype, "name", void 0);
  36040. __decorate([
  36041. BABYLON.serialize()
  36042. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36043. __decorate([
  36044. BABYLON.serialize()
  36045. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36046. __decorate([
  36047. BABYLON.serialize()
  36048. ], Material.prototype, "state", void 0);
  36049. __decorate([
  36050. BABYLON.serialize("alpha")
  36051. ], Material.prototype, "_alpha", void 0);
  36052. __decorate([
  36053. BABYLON.serialize("backFaceCulling")
  36054. ], Material.prototype, "_backFaceCulling", void 0);
  36055. __decorate([
  36056. BABYLON.serialize()
  36057. ], Material.prototype, "sideOrientation", void 0);
  36058. __decorate([
  36059. BABYLON.serialize("alphaMode")
  36060. ], Material.prototype, "_alphaMode", void 0);
  36061. __decorate([
  36062. BABYLON.serialize()
  36063. ], Material.prototype, "_needDepthPrePass", void 0);
  36064. __decorate([
  36065. BABYLON.serialize()
  36066. ], Material.prototype, "disableDepthWrite", void 0);
  36067. __decorate([
  36068. BABYLON.serialize()
  36069. ], Material.prototype, "forceDepthWrite", void 0);
  36070. __decorate([
  36071. BABYLON.serialize()
  36072. ], Material.prototype, "separateCullingPass", void 0);
  36073. __decorate([
  36074. BABYLON.serialize("fogEnabled")
  36075. ], Material.prototype, "_fogEnabled", void 0);
  36076. __decorate([
  36077. BABYLON.serialize()
  36078. ], Material.prototype, "pointSize", void 0);
  36079. __decorate([
  36080. BABYLON.serialize()
  36081. ], Material.prototype, "zOffset", void 0);
  36082. __decorate([
  36083. BABYLON.serialize()
  36084. ], Material.prototype, "wireframe", null);
  36085. __decorate([
  36086. BABYLON.serialize()
  36087. ], Material.prototype, "pointsCloud", null);
  36088. __decorate([
  36089. BABYLON.serialize()
  36090. ], Material.prototype, "fillMode", null);
  36091. return Material;
  36092. }());
  36093. BABYLON.Material = Material;
  36094. })(BABYLON || (BABYLON = {}));
  36095. //# sourceMappingURL=babylon.material.js.map
  36096. var BABYLON;
  36097. (function (BABYLON) {
  36098. var UniformBuffer = /** @class */ (function () {
  36099. /**
  36100. * Uniform buffer objects.
  36101. *
  36102. * Handles blocks of uniform on the GPU.
  36103. *
  36104. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36105. *
  36106. * For more information, please refer to :
  36107. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36108. */
  36109. function UniformBuffer(engine, data, dynamic) {
  36110. this._engine = engine;
  36111. this._noUBO = !engine.supportsUniformBuffers;
  36112. this._dynamic = dynamic;
  36113. this._data = data || [];
  36114. this._uniformLocations = {};
  36115. this._uniformSizes = {};
  36116. this._uniformLocationPointer = 0;
  36117. this._needSync = false;
  36118. if (this._noUBO) {
  36119. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36120. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36121. this.updateFloat = this._updateFloatForEffect;
  36122. this.updateFloat2 = this._updateFloat2ForEffect;
  36123. this.updateFloat3 = this._updateFloat3ForEffect;
  36124. this.updateFloat4 = this._updateFloat4ForEffect;
  36125. this.updateMatrix = this._updateMatrixForEffect;
  36126. this.updateVector3 = this._updateVector3ForEffect;
  36127. this.updateVector4 = this._updateVector4ForEffect;
  36128. this.updateColor3 = this._updateColor3ForEffect;
  36129. this.updateColor4 = this._updateColor4ForEffect;
  36130. }
  36131. else {
  36132. this._engine._uniformBuffers.push(this);
  36133. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36134. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36135. this.updateFloat = this._updateFloatForUniform;
  36136. this.updateFloat2 = this._updateFloat2ForUniform;
  36137. this.updateFloat3 = this._updateFloat3ForUniform;
  36138. this.updateFloat4 = this._updateFloat4ForUniform;
  36139. this.updateMatrix = this._updateMatrixForUniform;
  36140. this.updateVector3 = this._updateVector3ForUniform;
  36141. this.updateVector4 = this._updateVector4ForUniform;
  36142. this.updateColor3 = this._updateColor3ForUniform;
  36143. this.updateColor4 = this._updateColor4ForUniform;
  36144. }
  36145. }
  36146. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36147. // Properties
  36148. /**
  36149. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36150. * or just falling back on setUniformXXX calls.
  36151. */
  36152. get: function () {
  36153. return !this._noUBO;
  36154. },
  36155. enumerable: true,
  36156. configurable: true
  36157. });
  36158. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36159. /**
  36160. * Indicates if the WebGL underlying uniform buffer is in sync
  36161. * with the javascript cache data.
  36162. */
  36163. get: function () {
  36164. return !this._needSync;
  36165. },
  36166. enumerable: true,
  36167. configurable: true
  36168. });
  36169. /**
  36170. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36171. * Also, a dynamic UniformBuffer will disable cache verification and always
  36172. * update the underlying WebGL uniform buffer to the GPU.
  36173. */
  36174. UniformBuffer.prototype.isDynamic = function () {
  36175. return this._dynamic !== undefined;
  36176. };
  36177. /**
  36178. * The data cache on JS side.
  36179. */
  36180. UniformBuffer.prototype.getData = function () {
  36181. return this._bufferData;
  36182. };
  36183. /**
  36184. * The underlying WebGL Uniform buffer.
  36185. */
  36186. UniformBuffer.prototype.getBuffer = function () {
  36187. return this._buffer;
  36188. };
  36189. /**
  36190. * std140 layout specifies how to align data within an UBO structure.
  36191. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36192. * for specs.
  36193. */
  36194. UniformBuffer.prototype._fillAlignment = function (size) {
  36195. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36196. // and 4x4 matrices
  36197. // TODO : change if other types are used
  36198. var alignment;
  36199. if (size <= 2) {
  36200. alignment = size;
  36201. }
  36202. else {
  36203. alignment = 4;
  36204. }
  36205. if ((this._uniformLocationPointer % alignment) !== 0) {
  36206. var oldPointer = this._uniformLocationPointer;
  36207. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36208. var diff = this._uniformLocationPointer - oldPointer;
  36209. for (var i = 0; i < diff; i++) {
  36210. this._data.push(0);
  36211. }
  36212. }
  36213. };
  36214. /**
  36215. * Adds an uniform in the buffer.
  36216. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36217. * for the layout to be correct !
  36218. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36219. * @param {number|number[]} size Data size, or data directly.
  36220. */
  36221. UniformBuffer.prototype.addUniform = function (name, size) {
  36222. if (this._noUBO) {
  36223. return;
  36224. }
  36225. if (this._uniformLocations[name] !== undefined) {
  36226. // Already existing uniform
  36227. return;
  36228. }
  36229. // This function must be called in the order of the shader layout !
  36230. // size can be the size of the uniform, or data directly
  36231. var data;
  36232. if (size instanceof Array) {
  36233. data = size;
  36234. size = data.length;
  36235. }
  36236. else {
  36237. size = size;
  36238. data = [];
  36239. // Fill with zeros
  36240. for (var i = 0; i < size; i++) {
  36241. data.push(0);
  36242. }
  36243. }
  36244. this._fillAlignment(size);
  36245. this._uniformSizes[name] = size;
  36246. this._uniformLocations[name] = this._uniformLocationPointer;
  36247. this._uniformLocationPointer += size;
  36248. for (var i = 0; i < size; i++) {
  36249. this._data.push(data[i]);
  36250. }
  36251. this._needSync = true;
  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 {Matrix} mat A 4x4 matrix.
  36257. */
  36258. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36259. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36260. };
  36261. /**
  36262. * Wrapper for addUniform.
  36263. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36264. * @param {number} x
  36265. * @param {number} y
  36266. */
  36267. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36268. var temp = [x, y];
  36269. this.addUniform(name, temp);
  36270. };
  36271. /**
  36272. * Wrapper for addUniform.
  36273. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36274. * @param {number} x
  36275. * @param {number} y
  36276. * @param {number} z
  36277. */
  36278. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36279. var temp = [x, y, z];
  36280. this.addUniform(name, temp);
  36281. };
  36282. /**
  36283. * Wrapper for addUniform.
  36284. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36285. * @param {Color3} color
  36286. */
  36287. UniformBuffer.prototype.addColor3 = function (name, color) {
  36288. var temp = new Array();
  36289. color.toArray(temp);
  36290. this.addUniform(name, temp);
  36291. };
  36292. /**
  36293. * Wrapper for addUniform.
  36294. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36295. * @param {Color3} color
  36296. * @param {number} alpha
  36297. */
  36298. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36299. var temp = new Array();
  36300. color.toArray(temp);
  36301. temp.push(alpha);
  36302. this.addUniform(name, temp);
  36303. };
  36304. /**
  36305. * Wrapper for addUniform.
  36306. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36307. * @param {Vector3} vector
  36308. */
  36309. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36310. var temp = new Array();
  36311. vector.toArray(temp);
  36312. this.addUniform(name, temp);
  36313. };
  36314. /**
  36315. * Wrapper for addUniform.
  36316. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36317. */
  36318. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36319. this.addUniform(name, 12);
  36320. };
  36321. /**
  36322. * Wrapper for addUniform.
  36323. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36324. */
  36325. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36326. this.addUniform(name, 8);
  36327. };
  36328. /**
  36329. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36330. */
  36331. UniformBuffer.prototype.create = function () {
  36332. if (this._noUBO) {
  36333. return;
  36334. }
  36335. if (this._buffer) {
  36336. return; // nothing to do
  36337. }
  36338. // See spec, alignment must be filled as a vec4
  36339. this._fillAlignment(4);
  36340. this._bufferData = new Float32Array(this._data);
  36341. this._rebuild();
  36342. this._needSync = true;
  36343. };
  36344. UniformBuffer.prototype._rebuild = function () {
  36345. if (this._noUBO) {
  36346. return;
  36347. }
  36348. if (this._dynamic) {
  36349. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36350. }
  36351. else {
  36352. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36353. }
  36354. };
  36355. /**
  36356. * Updates the WebGL Uniform Buffer on the GPU.
  36357. * If the `dynamic` flag is set to true, no cache comparison is done.
  36358. * Otherwise, the buffer will be updated only if the cache differs.
  36359. */
  36360. UniformBuffer.prototype.update = function () {
  36361. if (!this._buffer) {
  36362. this.create();
  36363. return;
  36364. }
  36365. if (!this._dynamic && !this._needSync) {
  36366. return;
  36367. }
  36368. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36369. this._needSync = false;
  36370. };
  36371. /**
  36372. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36373. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36374. * @param {number[]|Float32Array} data Flattened data
  36375. * @param {number} size Size of the data.
  36376. */
  36377. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36378. var location = this._uniformLocations[uniformName];
  36379. if (location === undefined) {
  36380. if (this._buffer) {
  36381. // Cannot add an uniform if the buffer is already created
  36382. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36383. return;
  36384. }
  36385. this.addUniform(uniformName, size);
  36386. location = this._uniformLocations[uniformName];
  36387. }
  36388. if (!this._buffer) {
  36389. this.create();
  36390. }
  36391. if (!this._dynamic) {
  36392. // Cache for static uniform buffers
  36393. var changed = false;
  36394. for (var i = 0; i < size; i++) {
  36395. if (this._bufferData[location + i] !== data[i]) {
  36396. changed = true;
  36397. this._bufferData[location + i] = data[i];
  36398. }
  36399. }
  36400. this._needSync = this._needSync || changed;
  36401. }
  36402. else {
  36403. // No cache for dynamic
  36404. for (var i = 0; i < size; i++) {
  36405. this._bufferData[location + i] = data[i];
  36406. }
  36407. }
  36408. };
  36409. // Update methods
  36410. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36411. // To match std140, matrix must be realigned
  36412. for (var i = 0; i < 3; i++) {
  36413. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36414. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36415. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36416. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36417. }
  36418. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36419. };
  36420. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36421. this._currentEffect.setMatrix3x3(name, matrix);
  36422. };
  36423. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36424. this._currentEffect.setMatrix2x2(name, matrix);
  36425. };
  36426. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36427. // To match std140, matrix must be realigned
  36428. for (var i = 0; i < 2; i++) {
  36429. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36430. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36431. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36432. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36433. }
  36434. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36435. };
  36436. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36437. this._currentEffect.setFloat(name, x);
  36438. };
  36439. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36440. UniformBuffer._tempBuffer[0] = x;
  36441. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36442. };
  36443. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36444. if (suffix === void 0) { suffix = ""; }
  36445. this._currentEffect.setFloat2(name + suffix, x, y);
  36446. };
  36447. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36448. if (suffix === void 0) { suffix = ""; }
  36449. UniformBuffer._tempBuffer[0] = x;
  36450. UniformBuffer._tempBuffer[1] = y;
  36451. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36452. };
  36453. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36454. if (suffix === void 0) { suffix = ""; }
  36455. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36456. };
  36457. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36458. if (suffix === void 0) { suffix = ""; }
  36459. UniformBuffer._tempBuffer[0] = x;
  36460. UniformBuffer._tempBuffer[1] = y;
  36461. UniformBuffer._tempBuffer[2] = z;
  36462. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36463. };
  36464. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36465. if (suffix === void 0) { suffix = ""; }
  36466. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36467. };
  36468. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36469. if (suffix === void 0) { suffix = ""; }
  36470. UniformBuffer._tempBuffer[0] = x;
  36471. UniformBuffer._tempBuffer[1] = y;
  36472. UniformBuffer._tempBuffer[2] = z;
  36473. UniformBuffer._tempBuffer[3] = w;
  36474. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36475. };
  36476. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36477. this._currentEffect.setMatrix(name, mat);
  36478. };
  36479. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36480. this.updateUniform(name, mat.toArray(), 16);
  36481. };
  36482. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36483. this._currentEffect.setVector3(name, vector);
  36484. };
  36485. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36486. vector.toArray(UniformBuffer._tempBuffer);
  36487. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36488. };
  36489. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36490. this._currentEffect.setVector4(name, vector);
  36491. };
  36492. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36493. vector.toArray(UniformBuffer._tempBuffer);
  36494. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36495. };
  36496. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36497. if (suffix === void 0) { suffix = ""; }
  36498. this._currentEffect.setColor3(name + suffix, color);
  36499. };
  36500. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36501. if (suffix === void 0) { suffix = ""; }
  36502. color.toArray(UniformBuffer._tempBuffer);
  36503. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36504. };
  36505. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36506. if (suffix === void 0) { suffix = ""; }
  36507. this._currentEffect.setColor4(name + suffix, color, alpha);
  36508. };
  36509. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36510. if (suffix === void 0) { suffix = ""; }
  36511. color.toArray(UniformBuffer._tempBuffer);
  36512. UniformBuffer._tempBuffer[3] = alpha;
  36513. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36514. };
  36515. /**
  36516. * Sets a sampler uniform on the effect.
  36517. * @param {string} name Name of the sampler.
  36518. * @param {Texture} texture
  36519. */
  36520. UniformBuffer.prototype.setTexture = function (name, texture) {
  36521. this._currentEffect.setTexture(name, texture);
  36522. };
  36523. /**
  36524. * Directly updates the value of the uniform in the cache AND on the GPU.
  36525. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36526. * @param {number[]|Float32Array} data Flattened data
  36527. */
  36528. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36529. this.updateUniform(uniformName, data, data.length);
  36530. this.update();
  36531. };
  36532. /**
  36533. * Binds this uniform buffer to an effect.
  36534. * @param {Effect} effect
  36535. * @param {string} name Name of the uniform block in the shader.
  36536. */
  36537. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36538. this._currentEffect = effect;
  36539. if (this._noUBO || !this._buffer) {
  36540. return;
  36541. }
  36542. effect.bindUniformBuffer(this._buffer, name);
  36543. };
  36544. /**
  36545. * Disposes the uniform buffer.
  36546. */
  36547. UniformBuffer.prototype.dispose = function () {
  36548. if (this._noUBO) {
  36549. return;
  36550. }
  36551. var index = this._engine._uniformBuffers.indexOf(this);
  36552. if (index !== -1) {
  36553. this._engine._uniformBuffers.splice(index, 1);
  36554. }
  36555. if (!this._buffer) {
  36556. return;
  36557. }
  36558. if (this._engine._releaseBuffer(this._buffer)) {
  36559. this._buffer = null;
  36560. }
  36561. };
  36562. // Pool for avoiding memory leaks
  36563. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36564. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36565. return UniformBuffer;
  36566. }());
  36567. BABYLON.UniformBuffer = UniformBuffer;
  36568. })(BABYLON || (BABYLON = {}));
  36569. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36570. var BABYLON;
  36571. (function (BABYLON) {
  36572. /**
  36573. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36574. */
  36575. var VertexData = /** @class */ (function () {
  36576. function VertexData() {
  36577. }
  36578. /**
  36579. * Uses the passed data array to set the set the values for the specified kind of data
  36580. * @param data a linear array of floating numbers
  36581. * @param kind the type of data that is being set, eg positions, colors etc
  36582. */
  36583. VertexData.prototype.set = function (data, kind) {
  36584. switch (kind) {
  36585. case BABYLON.VertexBuffer.PositionKind:
  36586. this.positions = data;
  36587. break;
  36588. case BABYLON.VertexBuffer.NormalKind:
  36589. this.normals = data;
  36590. break;
  36591. case BABYLON.VertexBuffer.TangentKind:
  36592. this.tangents = data;
  36593. break;
  36594. case BABYLON.VertexBuffer.UVKind:
  36595. this.uvs = data;
  36596. break;
  36597. case BABYLON.VertexBuffer.UV2Kind:
  36598. this.uvs2 = data;
  36599. break;
  36600. case BABYLON.VertexBuffer.UV3Kind:
  36601. this.uvs3 = data;
  36602. break;
  36603. case BABYLON.VertexBuffer.UV4Kind:
  36604. this.uvs4 = data;
  36605. break;
  36606. case BABYLON.VertexBuffer.UV5Kind:
  36607. this.uvs5 = data;
  36608. break;
  36609. case BABYLON.VertexBuffer.UV6Kind:
  36610. this.uvs6 = data;
  36611. break;
  36612. case BABYLON.VertexBuffer.ColorKind:
  36613. this.colors = data;
  36614. break;
  36615. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36616. this.matricesIndices = data;
  36617. break;
  36618. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36619. this.matricesWeights = data;
  36620. break;
  36621. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36622. this.matricesIndicesExtra = data;
  36623. break;
  36624. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36625. this.matricesWeightsExtra = data;
  36626. break;
  36627. }
  36628. };
  36629. /**
  36630. * Associates the vertexData to the passed Mesh.
  36631. * Sets it as updatable or not (default `false`)
  36632. * @param mesh the mesh the vertexData is applied to
  36633. * @param updatable when used and having the value true allows new data to update the vertexData
  36634. * @returns the VertexData
  36635. */
  36636. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36637. this._applyTo(mesh, updatable);
  36638. return this;
  36639. };
  36640. /**
  36641. * Associates the vertexData to the passed Geometry.
  36642. * Sets it as updatable or not (default `false`)
  36643. * @param geometry the geometry the vertexData is applied to
  36644. * @param updatable when used and having the value true allows new data to update the vertexData
  36645. * @returns VertexData
  36646. */
  36647. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36648. this._applyTo(geometry, updatable);
  36649. return this;
  36650. };
  36651. /**
  36652. * Updates the associated mesh
  36653. * @param mesh the mesh to be updated
  36654. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36655. * @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
  36656. * @returns VertexData
  36657. */
  36658. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36659. this._update(mesh);
  36660. return this;
  36661. };
  36662. /**
  36663. * Updates the associated geometry
  36664. * @param geometry the geometry to be updated
  36665. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36666. * @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
  36667. * @returns VertexData.
  36668. */
  36669. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36670. this._update(geometry);
  36671. return this;
  36672. };
  36673. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36674. if (updatable === void 0) { updatable = false; }
  36675. if (this.positions) {
  36676. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36677. }
  36678. if (this.normals) {
  36679. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36680. }
  36681. if (this.tangents) {
  36682. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36683. }
  36684. if (this.uvs) {
  36685. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36686. }
  36687. if (this.uvs2) {
  36688. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36689. }
  36690. if (this.uvs3) {
  36691. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36692. }
  36693. if (this.uvs4) {
  36694. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36695. }
  36696. if (this.uvs5) {
  36697. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36698. }
  36699. if (this.uvs6) {
  36700. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36701. }
  36702. if (this.colors) {
  36703. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36704. }
  36705. if (this.matricesIndices) {
  36706. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36707. }
  36708. if (this.matricesWeights) {
  36709. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36710. }
  36711. if (this.matricesIndicesExtra) {
  36712. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36713. }
  36714. if (this.matricesWeightsExtra) {
  36715. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36716. }
  36717. if (this.indices) {
  36718. meshOrGeometry.setIndices(this.indices, null, updatable);
  36719. }
  36720. else {
  36721. meshOrGeometry.setIndices([], null);
  36722. }
  36723. return this;
  36724. };
  36725. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36726. if (this.positions) {
  36727. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36728. }
  36729. if (this.normals) {
  36730. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36731. }
  36732. if (this.tangents) {
  36733. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36734. }
  36735. if (this.uvs) {
  36736. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36737. }
  36738. if (this.uvs2) {
  36739. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36740. }
  36741. if (this.uvs3) {
  36742. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36743. }
  36744. if (this.uvs4) {
  36745. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36746. }
  36747. if (this.uvs5) {
  36748. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36749. }
  36750. if (this.uvs6) {
  36751. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36752. }
  36753. if (this.colors) {
  36754. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36755. }
  36756. if (this.matricesIndices) {
  36757. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36758. }
  36759. if (this.matricesWeights) {
  36760. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36761. }
  36762. if (this.matricesIndicesExtra) {
  36763. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36764. }
  36765. if (this.matricesWeightsExtra) {
  36766. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36767. }
  36768. if (this.indices) {
  36769. meshOrGeometry.setIndices(this.indices, null);
  36770. }
  36771. return this;
  36772. };
  36773. /**
  36774. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36775. * @param matrix the transforming matrix
  36776. * @returns the VertexData
  36777. */
  36778. VertexData.prototype.transform = function (matrix) {
  36779. var transformed = BABYLON.Vector3.Zero();
  36780. var index;
  36781. if (this.positions) {
  36782. var position = BABYLON.Vector3.Zero();
  36783. for (index = 0; index < this.positions.length; index += 3) {
  36784. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36785. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36786. this.positions[index] = transformed.x;
  36787. this.positions[index + 1] = transformed.y;
  36788. this.positions[index + 2] = transformed.z;
  36789. }
  36790. }
  36791. if (this.normals) {
  36792. var normal = BABYLON.Vector3.Zero();
  36793. for (index = 0; index < this.normals.length; index += 3) {
  36794. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36795. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36796. this.normals[index] = transformed.x;
  36797. this.normals[index + 1] = transformed.y;
  36798. this.normals[index + 2] = transformed.z;
  36799. }
  36800. }
  36801. if (this.tangents) {
  36802. var tangent = BABYLON.Vector4.Zero();
  36803. var tangentTransformed = BABYLON.Vector4.Zero();
  36804. for (index = 0; index < this.tangents.length; index += 4) {
  36805. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36806. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36807. this.tangents[index] = tangentTransformed.x;
  36808. this.tangents[index + 1] = tangentTransformed.y;
  36809. this.tangents[index + 2] = tangentTransformed.z;
  36810. this.tangents[index + 3] = tangentTransformed.w;
  36811. }
  36812. }
  36813. return this;
  36814. };
  36815. /**
  36816. * Merges the passed VertexData into the current one
  36817. * @param other the VertexData to be merged into the current one
  36818. * @returns the modified VertexData
  36819. */
  36820. VertexData.prototype.merge = function (other) {
  36821. this._validate();
  36822. other._validate();
  36823. if (!this.normals !== !other.normals ||
  36824. !this.tangents !== !other.tangents ||
  36825. !this.uvs !== !other.uvs ||
  36826. !this.uvs2 !== !other.uvs2 ||
  36827. !this.uvs3 !== !other.uvs3 ||
  36828. !this.uvs4 !== !other.uvs4 ||
  36829. !this.uvs5 !== !other.uvs5 ||
  36830. !this.uvs6 !== !other.uvs6 ||
  36831. !this.colors !== !other.colors ||
  36832. !this.matricesIndices !== !other.matricesIndices ||
  36833. !this.matricesWeights !== !other.matricesWeights ||
  36834. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36835. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36836. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36837. }
  36838. if (other.indices) {
  36839. if (!this.indices) {
  36840. this.indices = [];
  36841. }
  36842. var offset = this.positions ? this.positions.length / 3 : 0;
  36843. for (var index = 0; index < other.indices.length; index++) {
  36844. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36845. this.indices.push(other.indices[index] + offset);
  36846. }
  36847. }
  36848. this.positions = this._mergeElement(this.positions, other.positions);
  36849. this.normals = this._mergeElement(this.normals, other.normals);
  36850. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36851. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36852. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36853. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36854. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36855. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36856. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36857. this.colors = this._mergeElement(this.colors, other.colors);
  36858. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36859. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36860. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36861. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36862. return this;
  36863. };
  36864. VertexData.prototype._mergeElement = function (source, other) {
  36865. if (!source) {
  36866. return other;
  36867. }
  36868. if (!other) {
  36869. return source;
  36870. }
  36871. var len = other.length + source.length;
  36872. var isSrcTypedArray = source instanceof Float32Array;
  36873. var isOthTypedArray = other instanceof Float32Array;
  36874. // use non-loop method when the source is Float32Array
  36875. if (isSrcTypedArray) {
  36876. var ret32 = new Float32Array(len);
  36877. ret32.set(source);
  36878. ret32.set(other, source.length);
  36879. return ret32;
  36880. // source is number[], when other is also use concat
  36881. }
  36882. else if (!isOthTypedArray) {
  36883. return source.concat(other);
  36884. // source is a number[], but other is a Float32Array, loop required
  36885. }
  36886. else {
  36887. var ret = source.slice(0); // copy source to a separate array
  36888. for (var i = 0, len = other.length; i < len; i++) {
  36889. ret.push(other[i]);
  36890. }
  36891. return ret;
  36892. }
  36893. };
  36894. VertexData.prototype._validate = function () {
  36895. if (!this.positions) {
  36896. throw new Error("Positions are required");
  36897. }
  36898. var getElementCount = function (kind, values) {
  36899. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36900. if ((values.length % stride) !== 0) {
  36901. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36902. }
  36903. return values.length / stride;
  36904. };
  36905. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36906. var validateElementCount = function (kind, values) {
  36907. var elementCount = getElementCount(kind, values);
  36908. if (elementCount !== positionsElementCount) {
  36909. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36910. }
  36911. };
  36912. if (this.normals)
  36913. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36914. if (this.tangents)
  36915. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36916. if (this.uvs)
  36917. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36918. if (this.uvs2)
  36919. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36920. if (this.uvs3)
  36921. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36922. if (this.uvs4)
  36923. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36924. if (this.uvs5)
  36925. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36926. if (this.uvs6)
  36927. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36928. if (this.colors)
  36929. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36930. if (this.matricesIndices)
  36931. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36932. if (this.matricesWeights)
  36933. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36934. if (this.matricesIndicesExtra)
  36935. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36936. if (this.matricesWeightsExtra)
  36937. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36938. };
  36939. /**
  36940. * Serializes the VertexData
  36941. * @returns a serialized object
  36942. */
  36943. VertexData.prototype.serialize = function () {
  36944. var serializationObject = this.serialize();
  36945. if (this.positions) {
  36946. serializationObject.positions = this.positions;
  36947. }
  36948. if (this.normals) {
  36949. serializationObject.normals = this.normals;
  36950. }
  36951. if (this.tangents) {
  36952. serializationObject.tangents = this.tangents;
  36953. }
  36954. if (this.uvs) {
  36955. serializationObject.uvs = this.uvs;
  36956. }
  36957. if (this.uvs2) {
  36958. serializationObject.uvs2 = this.uvs2;
  36959. }
  36960. if (this.uvs3) {
  36961. serializationObject.uvs3 = this.uvs3;
  36962. }
  36963. if (this.uvs4) {
  36964. serializationObject.uvs4 = this.uvs4;
  36965. }
  36966. if (this.uvs5) {
  36967. serializationObject.uvs5 = this.uvs5;
  36968. }
  36969. if (this.uvs6) {
  36970. serializationObject.uvs6 = this.uvs6;
  36971. }
  36972. if (this.colors) {
  36973. serializationObject.colors = this.colors;
  36974. }
  36975. if (this.matricesIndices) {
  36976. serializationObject.matricesIndices = this.matricesIndices;
  36977. serializationObject.matricesIndices._isExpanded = true;
  36978. }
  36979. if (this.matricesWeights) {
  36980. serializationObject.matricesWeights = this.matricesWeights;
  36981. }
  36982. if (this.matricesIndicesExtra) {
  36983. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36984. serializationObject.matricesIndicesExtra._isExpanded = true;
  36985. }
  36986. if (this.matricesWeightsExtra) {
  36987. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36988. }
  36989. serializationObject.indices = this.indices;
  36990. return serializationObject;
  36991. };
  36992. // Statics
  36993. /**
  36994. * Extracts the vertexData from a mesh
  36995. * @param mesh the mesh from which to extract the VertexData
  36996. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36997. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36998. * @returns the object VertexData associated to the passed mesh
  36999. */
  37000. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  37001. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  37002. };
  37003. /**
  37004. * Extracts the vertexData from the geometry
  37005. * @param geometry the geometry from which to extract the VertexData
  37006. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  37007. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37008. * @returns the object VertexData associated to the passed mesh
  37009. */
  37010. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  37011. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  37012. };
  37013. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  37014. var result = new VertexData();
  37015. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37016. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  37017. }
  37018. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37019. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  37020. }
  37021. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37022. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  37023. }
  37024. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37025. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  37026. }
  37027. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37028. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37029. }
  37030. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37031. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  37032. }
  37033. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37034. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37035. }
  37036. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37037. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37038. }
  37039. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37040. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37041. }
  37042. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37043. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37044. }
  37045. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37046. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37047. }
  37048. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37049. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37050. }
  37051. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37052. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37053. }
  37054. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37055. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37056. }
  37057. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37058. return result;
  37059. };
  37060. /**
  37061. * Creates the VertexData for a Ribbon
  37062. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37063. * * pathArray array of paths, each of which an array of successive Vector3
  37064. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37065. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37066. * * 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
  37067. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37068. * * 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)
  37069. * * 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)
  37070. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37071. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37072. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37073. * @returns the VertexData of the ribbon
  37074. */
  37075. VertexData.CreateRibbon = function (options) {
  37076. var pathArray = options.pathArray;
  37077. var closeArray = options.closeArray || false;
  37078. var closePath = options.closePath || false;
  37079. var invertUV = options.invertUV || false;
  37080. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37081. var offset = options.offset || defaultOffset;
  37082. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37083. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37084. var customUV = options.uvs;
  37085. var customColors = options.colors;
  37086. var positions = [];
  37087. var indices = [];
  37088. var normals = [];
  37089. var uvs = [];
  37090. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37091. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37092. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37093. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37094. var minlg; // minimal length among all paths from pathArray
  37095. var lg = []; // array of path lengths : nb of vertex per path
  37096. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37097. var p; // path iterator
  37098. var i; // point iterator
  37099. var j; // point iterator
  37100. // if single path in pathArray
  37101. if (pathArray.length < 2) {
  37102. var ar1 = [];
  37103. var ar2 = [];
  37104. for (i = 0; i < pathArray[0].length - offset; i++) {
  37105. ar1.push(pathArray[0][i]);
  37106. ar2.push(pathArray[0][i + offset]);
  37107. }
  37108. pathArray = [ar1, ar2];
  37109. }
  37110. // positions and horizontal distances (u)
  37111. var idc = 0;
  37112. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37113. var path;
  37114. var l;
  37115. minlg = pathArray[0].length;
  37116. var vectlg;
  37117. var dist;
  37118. for (p = 0; p < pathArray.length; p++) {
  37119. uTotalDistance[p] = 0;
  37120. us[p] = [0];
  37121. path = pathArray[p];
  37122. l = path.length;
  37123. minlg = (minlg < l) ? minlg : l;
  37124. j = 0;
  37125. while (j < l) {
  37126. positions.push(path[j].x, path[j].y, path[j].z);
  37127. if (j > 0) {
  37128. vectlg = path[j].subtract(path[j - 1]).length();
  37129. dist = vectlg + uTotalDistance[p];
  37130. us[p].push(dist);
  37131. uTotalDistance[p] = dist;
  37132. }
  37133. j++;
  37134. }
  37135. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37136. j--;
  37137. positions.push(path[0].x, path[0].y, path[0].z);
  37138. vectlg = path[j].subtract(path[0]).length();
  37139. dist = vectlg + uTotalDistance[p];
  37140. us[p].push(dist);
  37141. uTotalDistance[p] = dist;
  37142. }
  37143. lg[p] = l + closePathCorr;
  37144. idx[p] = idc;
  37145. idc += (l + closePathCorr);
  37146. }
  37147. // vertical distances (v)
  37148. var path1;
  37149. var path2;
  37150. var vertex1 = null;
  37151. var vertex2 = null;
  37152. for (i = 0; i < minlg + closePathCorr; i++) {
  37153. vTotalDistance[i] = 0;
  37154. vs[i] = [0];
  37155. for (p = 0; p < pathArray.length - 1; p++) {
  37156. path1 = pathArray[p];
  37157. path2 = pathArray[p + 1];
  37158. if (i === minlg) { // closePath
  37159. vertex1 = path1[0];
  37160. vertex2 = path2[0];
  37161. }
  37162. else {
  37163. vertex1 = path1[i];
  37164. vertex2 = path2[i];
  37165. }
  37166. vectlg = vertex2.subtract(vertex1).length();
  37167. dist = vectlg + vTotalDistance[i];
  37168. vs[i].push(dist);
  37169. vTotalDistance[i] = dist;
  37170. }
  37171. if (closeArray && vertex2 && vertex1) {
  37172. path1 = pathArray[p];
  37173. path2 = pathArray[0];
  37174. if (i === minlg) { // closePath
  37175. vertex2 = path2[0];
  37176. }
  37177. vectlg = vertex2.subtract(vertex1).length();
  37178. dist = vectlg + vTotalDistance[i];
  37179. vTotalDistance[i] = dist;
  37180. }
  37181. }
  37182. // uvs
  37183. var u;
  37184. var v;
  37185. if (customUV) {
  37186. for (p = 0; p < customUV.length; p++) {
  37187. uvs.push(customUV[p].x, customUV[p].y);
  37188. }
  37189. }
  37190. else {
  37191. for (p = 0; p < pathArray.length; p++) {
  37192. for (i = 0; i < minlg + closePathCorr; i++) {
  37193. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37194. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37195. if (invertUV) {
  37196. uvs.push(v, u);
  37197. }
  37198. else {
  37199. uvs.push(u, v);
  37200. }
  37201. }
  37202. }
  37203. }
  37204. // indices
  37205. p = 0; // path index
  37206. var pi = 0; // positions array index
  37207. var l1 = lg[p] - 1; // path1 length
  37208. var l2 = lg[p + 1] - 1; // path2 length
  37209. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37210. var shft = idx[1] - idx[0]; // shift
  37211. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37212. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37213. // 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
  37214. indices.push(pi, pi + shft, pi + 1);
  37215. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37216. pi += 1;
  37217. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37218. p++;
  37219. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37220. shft = idx[0] - idx[p];
  37221. l1 = lg[p] - 1;
  37222. l2 = lg[0] - 1;
  37223. }
  37224. else {
  37225. shft = idx[p + 1] - idx[p];
  37226. l1 = lg[p] - 1;
  37227. l2 = lg[p + 1] - 1;
  37228. }
  37229. pi = idx[p];
  37230. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37231. }
  37232. }
  37233. // normals
  37234. VertexData.ComputeNormals(positions, indices, normals);
  37235. if (closePath) { // update both the first and last vertex normals to their average value
  37236. var indexFirst = 0;
  37237. var indexLast = 0;
  37238. for (p = 0; p < pathArray.length; p++) {
  37239. indexFirst = idx[p] * 3;
  37240. if (p + 1 < pathArray.length) {
  37241. indexLast = (idx[p + 1] - 1) * 3;
  37242. }
  37243. else {
  37244. indexLast = normals.length - 3;
  37245. }
  37246. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37247. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37248. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37249. normals[indexLast] = normals[indexFirst];
  37250. normals[indexLast + 1] = normals[indexFirst + 1];
  37251. normals[indexLast + 2] = normals[indexFirst + 2];
  37252. }
  37253. }
  37254. // sides
  37255. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37256. // Colors
  37257. var colors = null;
  37258. if (customColors) {
  37259. colors = new Float32Array(customColors.length * 4);
  37260. for (var c = 0; c < customColors.length; c++) {
  37261. colors[c * 4] = customColors[c].r;
  37262. colors[c * 4 + 1] = customColors[c].g;
  37263. colors[c * 4 + 2] = customColors[c].b;
  37264. colors[c * 4 + 3] = customColors[c].a;
  37265. }
  37266. }
  37267. // Result
  37268. var vertexData = new VertexData();
  37269. var positions32 = new Float32Array(positions);
  37270. var normals32 = new Float32Array(normals);
  37271. var uvs32 = new Float32Array(uvs);
  37272. vertexData.indices = indices;
  37273. vertexData.positions = positions32;
  37274. vertexData.normals = normals32;
  37275. vertexData.uvs = uvs32;
  37276. if (colors) {
  37277. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37278. }
  37279. if (closePath) {
  37280. vertexData._idx = idx;
  37281. }
  37282. return vertexData;
  37283. };
  37284. /**
  37285. * Creates the VertexData for a box
  37286. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37287. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37288. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37289. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37290. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37291. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37292. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37293. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37294. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37295. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37296. * @returns the VertexData of the box
  37297. */
  37298. VertexData.CreateBox = function (options) {
  37299. var normalsSource = [
  37300. new BABYLON.Vector3(0, 0, 1),
  37301. new BABYLON.Vector3(0, 0, -1),
  37302. new BABYLON.Vector3(1, 0, 0),
  37303. new BABYLON.Vector3(-1, 0, 0),
  37304. new BABYLON.Vector3(0, 1, 0),
  37305. new BABYLON.Vector3(0, -1, 0)
  37306. ];
  37307. var indices = [];
  37308. var positions = [];
  37309. var normals = [];
  37310. var uvs = [];
  37311. var width = options.width || options.size || 1;
  37312. var height = options.height || options.size || 1;
  37313. var depth = options.depth || options.size || 1;
  37314. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37315. var faceUV = options.faceUV || new Array(6);
  37316. var faceColors = options.faceColors;
  37317. var colors = [];
  37318. // default face colors and UV if undefined
  37319. for (var f = 0; f < 6; f++) {
  37320. if (faceUV[f] === undefined) {
  37321. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37322. }
  37323. if (faceColors && faceColors[f] === undefined) {
  37324. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37325. }
  37326. }
  37327. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37328. // Create each face in turn.
  37329. for (var index = 0; index < normalsSource.length; index++) {
  37330. var normal = normalsSource[index];
  37331. // Get two vectors perpendicular to the face normal and to each other.
  37332. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37333. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37334. // Six indices (two triangles) per face.
  37335. var verticesLength = positions.length / 3;
  37336. indices.push(verticesLength);
  37337. indices.push(verticesLength + 1);
  37338. indices.push(verticesLength + 2);
  37339. indices.push(verticesLength);
  37340. indices.push(verticesLength + 2);
  37341. indices.push(verticesLength + 3);
  37342. // Four vertices per face.
  37343. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37344. positions.push(vertex.x, vertex.y, vertex.z);
  37345. normals.push(normal.x, normal.y, normal.z);
  37346. uvs.push(faceUV[index].z, faceUV[index].w);
  37347. if (faceColors) {
  37348. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37349. }
  37350. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37351. positions.push(vertex.x, vertex.y, vertex.z);
  37352. normals.push(normal.x, normal.y, normal.z);
  37353. uvs.push(faceUV[index].x, faceUV[index].w);
  37354. if (faceColors) {
  37355. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37356. }
  37357. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37358. positions.push(vertex.x, vertex.y, vertex.z);
  37359. normals.push(normal.x, normal.y, normal.z);
  37360. uvs.push(faceUV[index].x, faceUV[index].y);
  37361. if (faceColors) {
  37362. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37363. }
  37364. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37365. positions.push(vertex.x, vertex.y, vertex.z);
  37366. normals.push(normal.x, normal.y, normal.z);
  37367. uvs.push(faceUV[index].z, faceUV[index].y);
  37368. if (faceColors) {
  37369. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37370. }
  37371. }
  37372. // sides
  37373. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37374. // Result
  37375. var vertexData = new VertexData();
  37376. vertexData.indices = indices;
  37377. vertexData.positions = positions;
  37378. vertexData.normals = normals;
  37379. vertexData.uvs = uvs;
  37380. if (faceColors) {
  37381. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37382. vertexData.colors = totalColors;
  37383. }
  37384. return vertexData;
  37385. };
  37386. /**
  37387. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37388. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37389. * * segments sets the number of horizontal strips optional, default 32
  37390. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37391. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37392. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37393. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37394. * * 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
  37395. * * 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
  37396. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37397. * * 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)
  37398. * * 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)
  37399. * @returns the VertexData of the ellipsoid
  37400. */
  37401. VertexData.CreateSphere = function (options) {
  37402. var segments = options.segments || 32;
  37403. var diameterX = options.diameterX || options.diameter || 1;
  37404. var diameterY = options.diameterY || options.diameter || 1;
  37405. var diameterZ = options.diameterZ || options.diameter || 1;
  37406. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37407. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37408. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37409. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37410. var totalZRotationSteps = 2 + segments;
  37411. var totalYRotationSteps = 2 * totalZRotationSteps;
  37412. var indices = [];
  37413. var positions = [];
  37414. var normals = [];
  37415. var uvs = [];
  37416. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37417. var normalizedZ = zRotationStep / totalZRotationSteps;
  37418. var angleZ = normalizedZ * Math.PI * slice;
  37419. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37420. var normalizedY = yRotationStep / totalYRotationSteps;
  37421. var angleY = normalizedY * Math.PI * 2 * arc;
  37422. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37423. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37424. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37425. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37426. var vertex = complete.multiply(radius);
  37427. var normal = complete.divide(radius).normalize();
  37428. positions.push(vertex.x, vertex.y, vertex.z);
  37429. normals.push(normal.x, normal.y, normal.z);
  37430. uvs.push(normalizedY, normalizedZ);
  37431. }
  37432. if (zRotationStep > 0) {
  37433. var verticesCount = positions.length / 3;
  37434. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37435. indices.push((firstIndex));
  37436. indices.push((firstIndex + 1));
  37437. indices.push(firstIndex + totalYRotationSteps + 1);
  37438. indices.push((firstIndex + totalYRotationSteps + 1));
  37439. indices.push((firstIndex + 1));
  37440. indices.push((firstIndex + totalYRotationSteps + 2));
  37441. }
  37442. }
  37443. }
  37444. // Sides
  37445. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37446. // Result
  37447. var vertexData = new VertexData();
  37448. vertexData.indices = indices;
  37449. vertexData.positions = positions;
  37450. vertexData.normals = normals;
  37451. vertexData.uvs = uvs;
  37452. return vertexData;
  37453. };
  37454. /**
  37455. * Creates the VertexData for a cylinder, cone or prism
  37456. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37457. * * height sets the height (y direction) of the cylinder, optional, default 2
  37458. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37459. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37460. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37461. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37462. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37463. * * 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
  37464. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37465. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37466. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37467. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37468. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37469. * * 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)
  37470. * * 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)
  37471. * @returns the VertexData of the cylinder, cone or prism
  37472. */
  37473. VertexData.CreateCylinder = function (options) {
  37474. var height = options.height || 2;
  37475. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37476. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37477. var tessellation = options.tessellation || 24;
  37478. var subdivisions = options.subdivisions || 1;
  37479. var hasRings = options.hasRings ? true : false;
  37480. var enclose = options.enclose ? true : false;
  37481. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37482. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37483. var faceUV = options.faceUV || new Array(3);
  37484. var faceColors = options.faceColors;
  37485. // default face colors and UV if undefined
  37486. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37487. var ringNb = (hasRings) ? subdivisions : 1;
  37488. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37489. var f;
  37490. for (f = 0; f < surfaceNb; f++) {
  37491. if (faceColors && faceColors[f] === undefined) {
  37492. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37493. }
  37494. }
  37495. for (f = 0; f < surfaceNb; f++) {
  37496. if (faceUV && faceUV[f] === undefined) {
  37497. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37498. }
  37499. }
  37500. var indices = new Array();
  37501. var positions = new Array();
  37502. var normals = new Array();
  37503. var uvs = new Array();
  37504. var colors = new Array();
  37505. var angle_step = Math.PI * 2 * arc / tessellation;
  37506. var angle;
  37507. var h;
  37508. var radius;
  37509. var tan = (diameterBottom - diameterTop) / 2 / height;
  37510. var ringVertex = BABYLON.Vector3.Zero();
  37511. var ringNormal = BABYLON.Vector3.Zero();
  37512. var ringFirstVertex = BABYLON.Vector3.Zero();
  37513. var ringFirstNormal = BABYLON.Vector3.Zero();
  37514. var quadNormal = BABYLON.Vector3.Zero();
  37515. var Y = BABYLON.Axis.Y;
  37516. // positions, normals, uvs
  37517. var i;
  37518. var j;
  37519. var r;
  37520. var ringIdx = 1;
  37521. var s = 1; // surface index
  37522. var cs = 0;
  37523. var v = 0;
  37524. for (i = 0; i <= subdivisions; i++) {
  37525. h = i / subdivisions;
  37526. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37527. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37528. for (r = 0; r < ringIdx; r++) {
  37529. if (hasRings) {
  37530. s += r;
  37531. }
  37532. if (enclose) {
  37533. s += 2 * r;
  37534. }
  37535. for (j = 0; j <= tessellation; j++) {
  37536. angle = j * angle_step;
  37537. // position
  37538. ringVertex.x = Math.cos(-angle) * radius;
  37539. ringVertex.y = -height / 2 + h * height;
  37540. ringVertex.z = Math.sin(-angle) * radius;
  37541. // normal
  37542. if (diameterTop === 0 && i === subdivisions) {
  37543. // if no top cap, reuse former normals
  37544. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37545. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37546. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37547. }
  37548. else {
  37549. ringNormal.x = ringVertex.x;
  37550. ringNormal.z = ringVertex.z;
  37551. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37552. ringNormal.normalize();
  37553. }
  37554. // keep first ring vertex values for enclose
  37555. if (j === 0) {
  37556. ringFirstVertex.copyFrom(ringVertex);
  37557. ringFirstNormal.copyFrom(ringNormal);
  37558. }
  37559. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37560. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37561. if (hasRings) {
  37562. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37563. }
  37564. else {
  37565. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37566. }
  37567. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37568. if (faceColors) {
  37569. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37570. }
  37571. }
  37572. // if enclose, add four vertices and their dedicated normals
  37573. if (arc !== 1 && enclose) {
  37574. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37575. positions.push(0, ringVertex.y, 0);
  37576. positions.push(0, ringVertex.y, 0);
  37577. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37578. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37579. quadNormal.normalize();
  37580. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37581. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37582. quadNormal.normalize();
  37583. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37584. if (hasRings) {
  37585. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37586. }
  37587. else {
  37588. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37589. }
  37590. uvs.push(faceUV[s + 1].x, v);
  37591. uvs.push(faceUV[s + 1].z, v);
  37592. if (hasRings) {
  37593. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37594. }
  37595. else {
  37596. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37597. }
  37598. uvs.push(faceUV[s + 2].x, v);
  37599. uvs.push(faceUV[s + 2].z, v);
  37600. if (faceColors) {
  37601. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37602. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37603. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37604. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37605. }
  37606. }
  37607. if (cs !== s) {
  37608. cs = s;
  37609. }
  37610. }
  37611. }
  37612. // indices
  37613. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37614. var s;
  37615. i = 0;
  37616. for (s = 0; s < subdivisions; s++) {
  37617. var i0 = 0;
  37618. var i1 = 0;
  37619. var i2 = 0;
  37620. var i3 = 0;
  37621. for (j = 0; j < tessellation; j++) {
  37622. i0 = i * (e + 1) + j;
  37623. i1 = (i + 1) * (e + 1) + j;
  37624. i2 = i * (e + 1) + (j + 1);
  37625. i3 = (i + 1) * (e + 1) + (j + 1);
  37626. indices.push(i0, i1, i2);
  37627. indices.push(i3, i2, i1);
  37628. }
  37629. if (arc !== 1 && enclose) { // if enclose, add two quads
  37630. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37631. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37632. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37633. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37634. }
  37635. i = (hasRings) ? (i + 2) : (i + 1);
  37636. }
  37637. // Caps
  37638. var createCylinderCap = function (isTop) {
  37639. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37640. if (radius === 0) {
  37641. return;
  37642. }
  37643. // Cap positions, normals & uvs
  37644. var angle;
  37645. var circleVector;
  37646. var i;
  37647. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37648. var c = null;
  37649. if (faceColors) {
  37650. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37651. }
  37652. // cap center
  37653. var vbase = positions.length / 3;
  37654. var offset = isTop ? height / 2 : -height / 2;
  37655. var center = new BABYLON.Vector3(0, offset, 0);
  37656. positions.push(center.x, center.y, center.z);
  37657. normals.push(0, isTop ? 1 : -1, 0);
  37658. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37659. if (c) {
  37660. colors.push(c.r, c.g, c.b, c.a);
  37661. }
  37662. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37663. for (i = 0; i <= tessellation; i++) {
  37664. angle = Math.PI * 2 * i * arc / tessellation;
  37665. var cos = Math.cos(-angle);
  37666. var sin = Math.sin(-angle);
  37667. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37668. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37669. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37670. normals.push(0, isTop ? 1 : -1, 0);
  37671. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37672. if (c) {
  37673. colors.push(c.r, c.g, c.b, c.a);
  37674. }
  37675. }
  37676. // Cap indices
  37677. for (i = 0; i < tessellation; i++) {
  37678. if (!isTop) {
  37679. indices.push(vbase);
  37680. indices.push(vbase + (i + 1));
  37681. indices.push(vbase + (i + 2));
  37682. }
  37683. else {
  37684. indices.push(vbase);
  37685. indices.push(vbase + (i + 2));
  37686. indices.push(vbase + (i + 1));
  37687. }
  37688. }
  37689. };
  37690. // add caps to geometry
  37691. createCylinderCap(false);
  37692. createCylinderCap(true);
  37693. // Sides
  37694. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37695. var vertexData = new VertexData();
  37696. vertexData.indices = indices;
  37697. vertexData.positions = positions;
  37698. vertexData.normals = normals;
  37699. vertexData.uvs = uvs;
  37700. if (faceColors) {
  37701. vertexData.colors = colors;
  37702. }
  37703. return vertexData;
  37704. };
  37705. /**
  37706. * Creates the VertexData for a torus
  37707. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37708. * * diameter the diameter of the torus, optional default 1
  37709. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37710. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37711. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37712. * * 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)
  37713. * * 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)
  37714. * @returns the VertexData of the torus
  37715. */
  37716. VertexData.CreateTorus = function (options) {
  37717. var indices = [];
  37718. var positions = [];
  37719. var normals = [];
  37720. var uvs = [];
  37721. var diameter = options.diameter || 1;
  37722. var thickness = options.thickness || 0.5;
  37723. var tessellation = options.tessellation || 16;
  37724. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37725. var stride = tessellation + 1;
  37726. for (var i = 0; i <= tessellation; i++) {
  37727. var u = i / tessellation;
  37728. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37729. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37730. for (var j = 0; j <= tessellation; j++) {
  37731. var v = 1 - j / tessellation;
  37732. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37733. var dx = Math.cos(innerAngle);
  37734. var dy = Math.sin(innerAngle);
  37735. // Create a vertex.
  37736. var normal = new BABYLON.Vector3(dx, dy, 0);
  37737. var position = normal.scale(thickness / 2);
  37738. var textureCoordinate = new BABYLON.Vector2(u, v);
  37739. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37740. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37741. positions.push(position.x, position.y, position.z);
  37742. normals.push(normal.x, normal.y, normal.z);
  37743. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37744. // And create indices for two triangles.
  37745. var nextI = (i + 1) % stride;
  37746. var nextJ = (j + 1) % stride;
  37747. indices.push(i * stride + j);
  37748. indices.push(i * stride + nextJ);
  37749. indices.push(nextI * stride + j);
  37750. indices.push(i * stride + nextJ);
  37751. indices.push(nextI * stride + nextJ);
  37752. indices.push(nextI * stride + j);
  37753. }
  37754. }
  37755. // Sides
  37756. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37757. // Result
  37758. var vertexData = new VertexData();
  37759. vertexData.indices = indices;
  37760. vertexData.positions = positions;
  37761. vertexData.normals = normals;
  37762. vertexData.uvs = uvs;
  37763. return vertexData;
  37764. };
  37765. /**
  37766. * Creates the VertexData of the LineSystem
  37767. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37768. * - lines an array of lines, each line being an array of successive Vector3
  37769. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37770. * @returns the VertexData of the LineSystem
  37771. */
  37772. VertexData.CreateLineSystem = function (options) {
  37773. var indices = [];
  37774. var positions = [];
  37775. var lines = options.lines;
  37776. var colors = options.colors;
  37777. var vertexColors = [];
  37778. var idx = 0;
  37779. for (var l = 0; l < lines.length; l++) {
  37780. var points = lines[l];
  37781. for (var index = 0; index < points.length; index++) {
  37782. positions.push(points[index].x, points[index].y, points[index].z);
  37783. if (colors) {
  37784. var color = colors[l];
  37785. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37786. }
  37787. if (index > 0) {
  37788. indices.push(idx - 1);
  37789. indices.push(idx);
  37790. }
  37791. idx++;
  37792. }
  37793. }
  37794. var vertexData = new VertexData();
  37795. vertexData.indices = indices;
  37796. vertexData.positions = positions;
  37797. if (colors) {
  37798. vertexData.colors = vertexColors;
  37799. }
  37800. return vertexData;
  37801. };
  37802. /**
  37803. * Create the VertexData for a DashedLines
  37804. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37805. * - points an array successive Vector3
  37806. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37807. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37808. * - dashNb the intended total number of dashes, optional, default 200
  37809. * @returns the VertexData for the DashedLines
  37810. */
  37811. VertexData.CreateDashedLines = function (options) {
  37812. var dashSize = options.dashSize || 3;
  37813. var gapSize = options.gapSize || 1;
  37814. var dashNb = options.dashNb || 200;
  37815. var points = options.points;
  37816. var positions = new Array();
  37817. var indices = new Array();
  37818. var curvect = BABYLON.Vector3.Zero();
  37819. var lg = 0;
  37820. var nb = 0;
  37821. var shft = 0;
  37822. var dashshft = 0;
  37823. var curshft = 0;
  37824. var idx = 0;
  37825. var i = 0;
  37826. for (i = 0; i < points.length - 1; i++) {
  37827. points[i + 1].subtractToRef(points[i], curvect);
  37828. lg += curvect.length();
  37829. }
  37830. shft = lg / dashNb;
  37831. dashshft = dashSize * shft / (dashSize + gapSize);
  37832. for (i = 0; i < points.length - 1; i++) {
  37833. points[i + 1].subtractToRef(points[i], curvect);
  37834. nb = Math.floor(curvect.length() / shft);
  37835. curvect.normalize();
  37836. for (var j = 0; j < nb; j++) {
  37837. curshft = shft * j;
  37838. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37839. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37840. indices.push(idx, idx + 1);
  37841. idx += 2;
  37842. }
  37843. }
  37844. // Result
  37845. var vertexData = new VertexData();
  37846. vertexData.positions = positions;
  37847. vertexData.indices = indices;
  37848. return vertexData;
  37849. };
  37850. /**
  37851. * Creates the VertexData for a Ground
  37852. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37853. * - width the width (x direction) of the ground, optional, default 1
  37854. * - height the height (z direction) of the ground, optional, default 1
  37855. * - subdivisions the number of subdivisions per side, optional, default 1
  37856. * @returns the VertexData of the Ground
  37857. */
  37858. VertexData.CreateGround = function (options) {
  37859. var indices = [];
  37860. var positions = [];
  37861. var normals = [];
  37862. var uvs = [];
  37863. var row, col;
  37864. var width = options.width || 1;
  37865. var height = options.height || 1;
  37866. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37867. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37868. for (row = 0; row <= subdivisionsY; row++) {
  37869. for (col = 0; col <= subdivisionsX; col++) {
  37870. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37871. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37872. positions.push(position.x, position.y, position.z);
  37873. normals.push(normal.x, normal.y, normal.z);
  37874. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37875. }
  37876. }
  37877. for (row = 0; row < subdivisionsY; row++) {
  37878. for (col = 0; col < subdivisionsX; col++) {
  37879. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37880. indices.push(col + 1 + row * (subdivisionsX + 1));
  37881. indices.push(col + row * (subdivisionsX + 1));
  37882. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37883. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37884. indices.push(col + row * (subdivisionsX + 1));
  37885. }
  37886. }
  37887. // Result
  37888. var vertexData = new VertexData();
  37889. vertexData.indices = indices;
  37890. vertexData.positions = positions;
  37891. vertexData.normals = normals;
  37892. vertexData.uvs = uvs;
  37893. return vertexData;
  37894. };
  37895. /**
  37896. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37897. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37898. * * xmin the ground minimum X coordinate, optional, default -1
  37899. * * zmin the ground minimum Z coordinate, optional, default -1
  37900. * * xmax the ground maximum X coordinate, optional, default 1
  37901. * * zmax the ground maximum Z coordinate, optional, default 1
  37902. * * 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}
  37903. * * 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}
  37904. * @returns the VertexData of the TiledGround
  37905. */
  37906. VertexData.CreateTiledGround = function (options) {
  37907. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37908. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37909. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37910. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37911. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37912. var precision = options.precision || { w: 1, h: 1 };
  37913. var indices = new Array();
  37914. var positions = new Array();
  37915. var normals = new Array();
  37916. var uvs = new Array();
  37917. var row, col, tileRow, tileCol;
  37918. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37919. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37920. precision.w = (precision.w < 1) ? 1 : precision.w;
  37921. precision.h = (precision.h < 1) ? 1 : precision.h;
  37922. var tileSize = {
  37923. 'w': (xmax - xmin) / subdivisions.w,
  37924. 'h': (zmax - zmin) / subdivisions.h
  37925. };
  37926. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37927. // Indices
  37928. var base = positions.length / 3;
  37929. var rowLength = precision.w + 1;
  37930. for (row = 0; row < precision.h; row++) {
  37931. for (col = 0; col < precision.w; col++) {
  37932. var square = [
  37933. base + col + row * rowLength,
  37934. base + (col + 1) + row * rowLength,
  37935. base + (col + 1) + (row + 1) * rowLength,
  37936. base + col + (row + 1) * rowLength
  37937. ];
  37938. indices.push(square[1]);
  37939. indices.push(square[2]);
  37940. indices.push(square[3]);
  37941. indices.push(square[0]);
  37942. indices.push(square[1]);
  37943. indices.push(square[3]);
  37944. }
  37945. }
  37946. // Position, normals and uvs
  37947. var position = BABYLON.Vector3.Zero();
  37948. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37949. for (row = 0; row <= precision.h; row++) {
  37950. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37951. for (col = 0; col <= precision.w; col++) {
  37952. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37953. position.y = 0;
  37954. positions.push(position.x, position.y, position.z);
  37955. normals.push(normal.x, normal.y, normal.z);
  37956. uvs.push(col / precision.w, row / precision.h);
  37957. }
  37958. }
  37959. }
  37960. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37961. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37962. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37963. }
  37964. }
  37965. // Result
  37966. var vertexData = new VertexData();
  37967. vertexData.indices = indices;
  37968. vertexData.positions = positions;
  37969. vertexData.normals = normals;
  37970. vertexData.uvs = uvs;
  37971. return vertexData;
  37972. };
  37973. /**
  37974. * Creates the VertexData of the Ground designed from a heightmap
  37975. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37976. * * width the width (x direction) of the ground
  37977. * * height the height (z direction) of the ground
  37978. * * subdivisions the number of subdivisions per side
  37979. * * minHeight the minimum altitude on the ground, optional, default 0
  37980. * * maxHeight the maximum altitude on the ground, optional default 1
  37981. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37982. * * buffer the array holding the image color data
  37983. * * bufferWidth the width of image
  37984. * * bufferHeight the height of image
  37985. * @returns the VertexData of the Ground designed from a heightmap
  37986. */
  37987. VertexData.CreateGroundFromHeightMap = function (options) {
  37988. var indices = [];
  37989. var positions = [];
  37990. var normals = [];
  37991. var uvs = [];
  37992. var row, col;
  37993. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37994. // Vertices
  37995. for (row = 0; row <= options.subdivisions; row++) {
  37996. for (col = 0; col <= options.subdivisions; col++) {
  37997. 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));
  37998. // Compute height
  37999. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38000. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38001. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  38002. var r = options.buffer[pos] / 255.0;
  38003. var g = options.buffer[pos + 1] / 255.0;
  38004. var b = options.buffer[pos + 2] / 255.0;
  38005. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38006. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38007. // Add vertex
  38008. positions.push(position.x, position.y, position.z);
  38009. normals.push(0, 0, 0);
  38010. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38011. }
  38012. }
  38013. // Indices
  38014. for (row = 0; row < options.subdivisions; row++) {
  38015. for (col = 0; col < options.subdivisions; col++) {
  38016. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38017. indices.push(col + 1 + row * (options.subdivisions + 1));
  38018. indices.push(col + row * (options.subdivisions + 1));
  38019. indices.push(col + (row + 1) * (options.subdivisions + 1));
  38020. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38021. indices.push(col + row * (options.subdivisions + 1));
  38022. }
  38023. }
  38024. // Normals
  38025. VertexData.ComputeNormals(positions, indices, normals);
  38026. // Result
  38027. var vertexData = new VertexData();
  38028. vertexData.indices = indices;
  38029. vertexData.positions = positions;
  38030. vertexData.normals = normals;
  38031. vertexData.uvs = uvs;
  38032. return vertexData;
  38033. };
  38034. /**
  38035. * Creates the VertexData for a Plane
  38036. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  38037. * * size sets the width and height of the plane to the value of size, optional default 1
  38038. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38039. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  38040. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38041. * * 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)
  38042. * * 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)
  38043. * @returns the VertexData of the box
  38044. */
  38045. VertexData.CreatePlane = function (options) {
  38046. var indices = [];
  38047. var positions = [];
  38048. var normals = [];
  38049. var uvs = [];
  38050. var width = options.width || options.size || 1;
  38051. var height = options.height || options.size || 1;
  38052. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38053. // Vertices
  38054. var halfWidth = width / 2.0;
  38055. var halfHeight = height / 2.0;
  38056. positions.push(-halfWidth, -halfHeight, 0);
  38057. normals.push(0, 0, -1.0);
  38058. uvs.push(0.0, 0.0);
  38059. positions.push(halfWidth, -halfHeight, 0);
  38060. normals.push(0, 0, -1.0);
  38061. uvs.push(1.0, 0.0);
  38062. positions.push(halfWidth, halfHeight, 0);
  38063. normals.push(0, 0, -1.0);
  38064. uvs.push(1.0, 1.0);
  38065. positions.push(-halfWidth, halfHeight, 0);
  38066. normals.push(0, 0, -1.0);
  38067. uvs.push(0.0, 1.0);
  38068. // Indices
  38069. indices.push(0);
  38070. indices.push(1);
  38071. indices.push(2);
  38072. indices.push(0);
  38073. indices.push(2);
  38074. indices.push(3);
  38075. // Sides
  38076. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38077. // Result
  38078. var vertexData = new VertexData();
  38079. vertexData.indices = indices;
  38080. vertexData.positions = positions;
  38081. vertexData.normals = normals;
  38082. vertexData.uvs = uvs;
  38083. return vertexData;
  38084. };
  38085. /**
  38086. * Creates the VertexData of the Disc or regular Polygon
  38087. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38088. * * radius the radius of the disc, optional default 0.5
  38089. * * tessellation the number of polygon sides, optional, default 64
  38090. * * 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
  38091. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38092. * * 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)
  38093. * * 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)
  38094. * @returns the VertexData of the box
  38095. */
  38096. VertexData.CreateDisc = function (options) {
  38097. var positions = new Array();
  38098. var indices = new Array();
  38099. var normals = new Array();
  38100. var uvs = new Array();
  38101. var radius = options.radius || 0.5;
  38102. var tessellation = options.tessellation || 64;
  38103. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38104. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38105. // positions and uvs
  38106. positions.push(0, 0, 0); // disc center first
  38107. uvs.push(0.5, 0.5);
  38108. var theta = Math.PI * 2 * arc;
  38109. var step = theta / tessellation;
  38110. for (var a = 0; a < theta; a += step) {
  38111. var x = Math.cos(a);
  38112. var y = Math.sin(a);
  38113. var u = (x + 1) / 2;
  38114. var v = (1 - y) / 2;
  38115. positions.push(radius * x, radius * y, 0);
  38116. uvs.push(u, v);
  38117. }
  38118. if (arc === 1) {
  38119. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38120. uvs.push(uvs[2], uvs[3]);
  38121. }
  38122. //indices
  38123. var vertexNb = positions.length / 3;
  38124. for (var i = 1; i < vertexNb - 1; i++) {
  38125. indices.push(i + 1, 0, i);
  38126. }
  38127. // result
  38128. VertexData.ComputeNormals(positions, indices, normals);
  38129. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38130. var vertexData = new VertexData();
  38131. vertexData.indices = indices;
  38132. vertexData.positions = positions;
  38133. vertexData.normals = normals;
  38134. vertexData.uvs = uvs;
  38135. return vertexData;
  38136. };
  38137. /**
  38138. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38139. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38140. * @param polygon a mesh built from polygonTriangulation.build()
  38141. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38142. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38143. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38144. * @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)
  38145. * @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)
  38146. * @returns the VertexData of the Polygon
  38147. */
  38148. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38149. var faceUV = fUV || new Array(3);
  38150. var faceColors = fColors;
  38151. var colors = [];
  38152. // default face colors and UV if undefined
  38153. for (var f = 0; f < 3; f++) {
  38154. if (faceUV[f] === undefined) {
  38155. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38156. }
  38157. if (faceColors && faceColors[f] === undefined) {
  38158. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38159. }
  38160. }
  38161. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38162. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38163. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38164. var indices = polygon.getIndices();
  38165. // set face colours and textures
  38166. var idx = 0;
  38167. var face = 0;
  38168. for (var index = 0; index < normals.length; index += 3) {
  38169. //Edge Face no. 1
  38170. if (Math.abs(normals[index + 1]) < 0.001) {
  38171. face = 1;
  38172. }
  38173. //Top Face no. 0
  38174. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38175. face = 0;
  38176. }
  38177. //Bottom Face no. 2
  38178. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38179. face = 2;
  38180. }
  38181. idx = index / 3;
  38182. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38183. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38184. if (faceColors) {
  38185. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38186. }
  38187. }
  38188. // sides
  38189. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38190. // Result
  38191. var vertexData = new VertexData();
  38192. vertexData.indices = indices;
  38193. vertexData.positions = positions;
  38194. vertexData.normals = normals;
  38195. vertexData.uvs = uvs;
  38196. if (faceColors) {
  38197. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38198. vertexData.colors = totalColors;
  38199. }
  38200. return vertexData;
  38201. };
  38202. /**
  38203. * Creates the VertexData of the IcoSphere
  38204. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38205. * * radius the radius of the IcoSphere, optional default 1
  38206. * * radiusX allows stretching in the x direction, optional, default radius
  38207. * * radiusY allows stretching in the y direction, optional, default radius
  38208. * * radiusZ allows stretching in the z direction, optional, default radius
  38209. * * flat when true creates a flat shaded mesh, optional, default true
  38210. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38211. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38212. * * 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)
  38213. * * 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)
  38214. * @returns the VertexData of the IcoSphere
  38215. */
  38216. VertexData.CreateIcoSphere = function (options) {
  38217. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38218. var radius = options.radius || 1;
  38219. var flat = (options.flat === undefined) ? true : options.flat;
  38220. var subdivisions = options.subdivisions || 4;
  38221. var radiusX = options.radiusX || radius;
  38222. var radiusY = options.radiusY || radius;
  38223. var radiusZ = options.radiusZ || radius;
  38224. var t = (1 + Math.sqrt(5)) / 2;
  38225. // 12 vertex x,y,z
  38226. var ico_vertices = [
  38227. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38228. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38229. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38230. ];
  38231. // index of 3 vertex makes a face of icopshere
  38232. var ico_indices = [
  38233. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38234. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38235. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38236. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38237. ];
  38238. // vertex for uv have aliased position, not for UV
  38239. var vertices_unalias_id = [
  38240. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38241. // vertex alias
  38242. 0,
  38243. 2,
  38244. 3,
  38245. 3,
  38246. 3,
  38247. 4,
  38248. 7,
  38249. 8,
  38250. 9,
  38251. 9,
  38252. 10,
  38253. 11 // 23: B + 12
  38254. ];
  38255. // uv as integer step (not pixels !)
  38256. var ico_vertexuv = [
  38257. 5, 1, 3, 1, 6, 4, 0, 0,
  38258. 5, 3, 4, 2, 2, 2, 4, 0,
  38259. 2, 0, 1, 1, 6, 0, 6, 2,
  38260. // vertex alias (for same vertex on different faces)
  38261. 0, 4,
  38262. 3, 3,
  38263. 4, 4,
  38264. 3, 1,
  38265. 4, 2,
  38266. 4, 4,
  38267. 0, 2,
  38268. 1, 1,
  38269. 2, 2,
  38270. 3, 3,
  38271. 1, 3,
  38272. 2, 4 // 23: B + 12
  38273. ];
  38274. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38275. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38276. // First island of uv mapping
  38277. // v = 4h 3+ 2
  38278. // v = 3h 9+ 4
  38279. // v = 2h 9+ 5 B
  38280. // v = 1h 9 1 0
  38281. // v = 0h 3 8 7 A
  38282. // u = 0 1 2 3 4 5 6 *a
  38283. // Second island of uv mapping
  38284. // v = 4h 0+ B+ 4+
  38285. // v = 3h A+ 2+
  38286. // v = 2h 7+ 6 3+
  38287. // v = 1h 8+ 3+
  38288. // v = 0h
  38289. // u = 0 1 2 3 4 5 6 *a
  38290. // Face layout on texture UV mapping
  38291. // ============
  38292. // \ 4 /\ 16 / ======
  38293. // \ / \ / /\ 11 /
  38294. // \/ 7 \/ / \ /
  38295. // ======= / 10 \/
  38296. // /\ 17 /\ =======
  38297. // / \ / \ \ 15 /\
  38298. // / 8 \/ 12 \ \ / \
  38299. // ============ \/ 6 \
  38300. // \ 18 /\ ============
  38301. // \ / \ \ 5 /\ 0 /
  38302. // \/ 13 \ \ / \ /
  38303. // ======= \/ 1 \/
  38304. // =============
  38305. // /\ 19 /\ 2 /\
  38306. // / \ / \ / \
  38307. // / 14 \/ 9 \/ 3 \
  38308. // ===================
  38309. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38310. var ustep = 138 / 1024;
  38311. var vstep = 239 / 1024;
  38312. var uoffset = 60 / 1024;
  38313. var voffset = 26 / 1024;
  38314. // Second island should have margin, not to touch the first island
  38315. // avoid any borderline artefact in pixel rounding
  38316. var island_u_offset = -40 / 1024;
  38317. var island_v_offset = +20 / 1024;
  38318. // face is either island 0 or 1 :
  38319. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38320. var island = [
  38321. 0, 0, 0, 0, 1,
  38322. 0, 0, 1, 1, 0,
  38323. 0, 0, 1, 1, 0,
  38324. 0, 1, 1, 1, 0 // 15 - 19
  38325. ];
  38326. var indices = new Array();
  38327. var positions = new Array();
  38328. var normals = new Array();
  38329. var uvs = new Array();
  38330. var current_indice = 0;
  38331. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38332. var face_vertex_pos = new Array(3);
  38333. var face_vertex_uv = new Array(3);
  38334. var v012;
  38335. for (v012 = 0; v012 < 3; v012++) {
  38336. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38337. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38338. }
  38339. // create all with normals
  38340. for (var face = 0; face < 20; face++) {
  38341. // 3 vertex per face
  38342. for (v012 = 0; v012 < 3; v012++) {
  38343. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38344. var v_id = ico_indices[3 * face + v012];
  38345. // vertex have 3D position (x,y,z)
  38346. 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]);
  38347. // Normalize to get normal, then scale to radius
  38348. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38349. // uv Coordinates from vertex ID
  38350. 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);
  38351. }
  38352. // Subdivide the face (interpolate pos, norm, uv)
  38353. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38354. // - norm is linear interpolation of vertex corner normal
  38355. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38356. // - uv is linear interpolation
  38357. //
  38358. // Topology is as below for sub-divide by 2
  38359. // vertex shown as v0,v1,v2
  38360. // interp index is i1 to progress in range [v0,v1[
  38361. // interp index is i2 to progress in range [v0,v2[
  38362. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38363. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38364. //
  38365. //
  38366. // i2 v2
  38367. // ^ ^
  38368. // / / \
  38369. // / / \
  38370. // / / \
  38371. // / / (0,1) \
  38372. // / #---------\
  38373. // / / \ (0,0)'/ \
  38374. // / / \ / \
  38375. // / / \ / \
  38376. // / / (0,0) \ / (1,0) \
  38377. // / #---------#---------\
  38378. // v0 v1
  38379. //
  38380. // --------------------> i1
  38381. //
  38382. // interp of (i1,i2):
  38383. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38384. // along i1 : lerp(x0,x1, i1/(S-i2))
  38385. //
  38386. // centroid of triangle is needed to get help normal computation
  38387. // (c1,c2) are used for centroid location
  38388. var interp_vertex = function (i1, i2, c1, c2) {
  38389. // vertex is interpolated from
  38390. // - face_vertex_pos[0..2]
  38391. // - face_vertex_uv[0..2]
  38392. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38393. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38394. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38395. pos_interp.normalize();
  38396. var vertex_normal;
  38397. if (flat) {
  38398. // in flat mode, recalculate normal as face centroid normal
  38399. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38400. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38401. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38402. }
  38403. else {
  38404. // in smooth mode, recalculate normal from each single vertex position
  38405. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38406. }
  38407. // Vertex normal need correction due to X,Y,Z radius scaling
  38408. vertex_normal.x /= radiusX;
  38409. vertex_normal.y /= radiusY;
  38410. vertex_normal.z /= radiusZ;
  38411. vertex_normal.normalize();
  38412. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38413. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38414. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38415. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38416. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38417. uvs.push(uv_interp.x, uv_interp.y);
  38418. // push each vertex has member of a face
  38419. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38420. indices.push(current_indice);
  38421. current_indice++;
  38422. };
  38423. for (var i2 = 0; i2 < subdivisions; i2++) {
  38424. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38425. // face : (i1,i2) for /\ :
  38426. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38427. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38428. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38429. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38430. if (i1 + i2 + 1 < subdivisions) {
  38431. // face : (i1,i2)' for \/ :
  38432. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38433. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38434. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38435. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38436. }
  38437. }
  38438. }
  38439. }
  38440. // Sides
  38441. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38442. // Result
  38443. var vertexData = new VertexData();
  38444. vertexData.indices = indices;
  38445. vertexData.positions = positions;
  38446. vertexData.normals = normals;
  38447. vertexData.uvs = uvs;
  38448. return vertexData;
  38449. };
  38450. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38451. /**
  38452. * Creates the VertexData for a Polyhedron
  38453. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38454. * * type provided types are:
  38455. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38456. * * 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)
  38457. * * size the size of the IcoSphere, optional default 1
  38458. * * sizeX allows stretching in the x direction, optional, default size
  38459. * * sizeY allows stretching in the y direction, optional, default size
  38460. * * sizeZ allows stretching in the z direction, optional, default size
  38461. * * 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
  38462. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38463. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38464. * * flat when true creates a flat shaded mesh, optional, default true
  38465. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38466. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38467. * * 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)
  38468. * * 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)
  38469. * @returns the VertexData of the Polyhedron
  38470. */
  38471. VertexData.CreatePolyhedron = function (options) {
  38472. // provided polyhedron types :
  38473. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38474. // 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)
  38475. var polyhedra = [];
  38476. 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]] };
  38477. 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]] };
  38478. polyhedra[2] = {
  38479. 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]],
  38480. 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]]
  38481. };
  38482. polyhedra[3] = {
  38483. 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]],
  38484. 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]]
  38485. };
  38486. polyhedra[4] = {
  38487. 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]],
  38488. 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]]
  38489. };
  38490. 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]] };
  38491. 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]] };
  38492. 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]] };
  38493. 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]] };
  38494. 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]] };
  38495. 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]] };
  38496. 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]] };
  38497. 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]] };
  38498. 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]] };
  38499. polyhedra[14] = {
  38500. 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]],
  38501. 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]]
  38502. };
  38503. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38504. var size = options.size;
  38505. var sizeX = options.sizeX || size || 1;
  38506. var sizeY = options.sizeY || size || 1;
  38507. var sizeZ = options.sizeZ || size || 1;
  38508. var data = options.custom || polyhedra[type];
  38509. var nbfaces = data.face.length;
  38510. var faceUV = options.faceUV || new Array(nbfaces);
  38511. var faceColors = options.faceColors;
  38512. var flat = (options.flat === undefined) ? true : options.flat;
  38513. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38514. var positions = new Array();
  38515. var indices = new Array();
  38516. var normals = new Array();
  38517. var uvs = new Array();
  38518. var colors = new Array();
  38519. var index = 0;
  38520. var faceIdx = 0; // face cursor in the array "indexes"
  38521. var indexes = new Array();
  38522. var i = 0;
  38523. var f = 0;
  38524. var u, v, ang, x, y, tmp;
  38525. // default face colors and UV if undefined
  38526. if (flat) {
  38527. for (f = 0; f < nbfaces; f++) {
  38528. if (faceColors && faceColors[f] === undefined) {
  38529. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38530. }
  38531. if (faceUV && faceUV[f] === undefined) {
  38532. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38533. }
  38534. }
  38535. }
  38536. if (!flat) {
  38537. for (i = 0; i < data.vertex.length; i++) {
  38538. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38539. uvs.push(0, 0);
  38540. }
  38541. for (f = 0; f < nbfaces; f++) {
  38542. for (i = 0; i < data.face[f].length - 2; i++) {
  38543. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38544. }
  38545. }
  38546. }
  38547. else {
  38548. for (f = 0; f < nbfaces; f++) {
  38549. var fl = data.face[f].length; // number of vertices of the current face
  38550. ang = 2 * Math.PI / fl;
  38551. x = 0.5 * Math.tan(ang / 2);
  38552. y = 0.5;
  38553. // positions, uvs, colors
  38554. for (i = 0; i < fl; i++) {
  38555. // positions
  38556. 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);
  38557. indexes.push(index);
  38558. index++;
  38559. // uvs
  38560. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38561. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38562. uvs.push(u, v);
  38563. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38564. y = x * Math.sin(ang) + y * Math.cos(ang);
  38565. x = tmp;
  38566. // colors
  38567. if (faceColors) {
  38568. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38569. }
  38570. }
  38571. // indices from indexes
  38572. for (i = 0; i < fl - 2; i++) {
  38573. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38574. }
  38575. faceIdx += fl;
  38576. }
  38577. }
  38578. VertexData.ComputeNormals(positions, indices, normals);
  38579. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38580. var vertexData = new VertexData();
  38581. vertexData.positions = positions;
  38582. vertexData.indices = indices;
  38583. vertexData.normals = normals;
  38584. vertexData.uvs = uvs;
  38585. if (faceColors && flat) {
  38586. vertexData.colors = colors;
  38587. }
  38588. return vertexData;
  38589. };
  38590. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38591. /**
  38592. * Creates the VertexData for a TorusKnot
  38593. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38594. * * radius the radius of the torus knot, optional, default 2
  38595. * * tube the thickness of the tube, optional, default 0.5
  38596. * * radialSegments the number of sides on each tube segments, optional, default 32
  38597. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38598. * * p the number of windings around the z axis, optional, default 2
  38599. * * q the number of windings around the x axis, optional, default 3
  38600. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38601. * * 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)
  38602. * * 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)
  38603. * @returns the VertexData of the Torus Knot
  38604. */
  38605. VertexData.CreateTorusKnot = function (options) {
  38606. var indices = new Array();
  38607. var positions = new Array();
  38608. var normals = new Array();
  38609. var uvs = new Array();
  38610. var radius = options.radius || 2;
  38611. var tube = options.tube || 0.5;
  38612. var radialSegments = options.radialSegments || 32;
  38613. var tubularSegments = options.tubularSegments || 32;
  38614. var p = options.p || 2;
  38615. var q = options.q || 3;
  38616. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38617. // Helper
  38618. var getPos = function (angle) {
  38619. var cu = Math.cos(angle);
  38620. var su = Math.sin(angle);
  38621. var quOverP = q / p * angle;
  38622. var cs = Math.cos(quOverP);
  38623. var tx = radius * (2 + cs) * 0.5 * cu;
  38624. var ty = radius * (2 + cs) * su * 0.5;
  38625. var tz = radius * Math.sin(quOverP) * 0.5;
  38626. return new BABYLON.Vector3(tx, ty, tz);
  38627. };
  38628. // Vertices
  38629. var i;
  38630. var j;
  38631. for (i = 0; i <= radialSegments; i++) {
  38632. var modI = i % radialSegments;
  38633. var u = modI / radialSegments * 2 * p * Math.PI;
  38634. var p1 = getPos(u);
  38635. var p2 = getPos(u + 0.01);
  38636. var tang = p2.subtract(p1);
  38637. var n = p2.add(p1);
  38638. var bitan = BABYLON.Vector3.Cross(tang, n);
  38639. n = BABYLON.Vector3.Cross(bitan, tang);
  38640. bitan.normalize();
  38641. n.normalize();
  38642. for (j = 0; j < tubularSegments; j++) {
  38643. var modJ = j % tubularSegments;
  38644. var v = modJ / tubularSegments * 2 * Math.PI;
  38645. var cx = -tube * Math.cos(v);
  38646. var cy = tube * Math.sin(v);
  38647. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38648. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38649. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38650. uvs.push(i / radialSegments);
  38651. uvs.push(j / tubularSegments);
  38652. }
  38653. }
  38654. for (i = 0; i < radialSegments; i++) {
  38655. for (j = 0; j < tubularSegments; j++) {
  38656. var jNext = (j + 1) % tubularSegments;
  38657. var a = i * tubularSegments + j;
  38658. var b = (i + 1) * tubularSegments + j;
  38659. var c = (i + 1) * tubularSegments + jNext;
  38660. var d = i * tubularSegments + jNext;
  38661. indices.push(d);
  38662. indices.push(b);
  38663. indices.push(a);
  38664. indices.push(d);
  38665. indices.push(c);
  38666. indices.push(b);
  38667. }
  38668. }
  38669. // Normals
  38670. VertexData.ComputeNormals(positions, indices, normals);
  38671. // Sides
  38672. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38673. // Result
  38674. var vertexData = new VertexData();
  38675. vertexData.indices = indices;
  38676. vertexData.positions = positions;
  38677. vertexData.normals = normals;
  38678. vertexData.uvs = uvs;
  38679. return vertexData;
  38680. };
  38681. // Tools
  38682. /**
  38683. * Compute normals for given positions and indices
  38684. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38685. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38686. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38687. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38688. * * facetNormals : optional array of facet normals (vector3)
  38689. * * facetPositions : optional array of facet positions (vector3)
  38690. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38691. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38692. * * bInfo : optional bounding info, required for facetPartitioning computation
  38693. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38694. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38695. * * useRightHandedSystem: optional boolean to for right handed system computation
  38696. * * depthSort : optional boolean to enable the facet depth sort computation
  38697. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38698. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38699. */
  38700. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38701. // temporary scalar variables
  38702. var index = 0; // facet index
  38703. var p1p2x = 0.0; // p1p2 vector x coordinate
  38704. var p1p2y = 0.0; // p1p2 vector y coordinate
  38705. var p1p2z = 0.0; // p1p2 vector z coordinate
  38706. var p3p2x = 0.0; // p3p2 vector x coordinate
  38707. var p3p2y = 0.0; // p3p2 vector y coordinate
  38708. var p3p2z = 0.0; // p3p2 vector z coordinate
  38709. var faceNormalx = 0.0; // facet normal x coordinate
  38710. var faceNormaly = 0.0; // facet normal y coordinate
  38711. var faceNormalz = 0.0; // facet normal z coordinate
  38712. var length = 0.0; // facet normal length before normalization
  38713. var v1x = 0; // vector1 x index in the positions array
  38714. var v1y = 0; // vector1 y index in the positions array
  38715. var v1z = 0; // vector1 z index in the positions array
  38716. var v2x = 0; // vector2 x index in the positions array
  38717. var v2y = 0; // vector2 y index in the positions array
  38718. var v2z = 0; // vector2 z index in the positions array
  38719. var v3x = 0; // vector3 x index in the positions array
  38720. var v3y = 0; // vector3 y index in the positions array
  38721. var v3z = 0; // vector3 z index in the positions array
  38722. var computeFacetNormals = false;
  38723. var computeFacetPositions = false;
  38724. var computeFacetPartitioning = false;
  38725. var computeDepthSort = false;
  38726. var faceNormalSign = 1;
  38727. var ratio = 0;
  38728. var distanceTo = null;
  38729. if (options) {
  38730. computeFacetNormals = (options.facetNormals) ? true : false;
  38731. computeFacetPositions = (options.facetPositions) ? true : false;
  38732. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38733. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38734. ratio = options.ratio || 0;
  38735. computeDepthSort = (options.depthSort) ? true : false;
  38736. distanceTo = (options.distanceTo);
  38737. if (computeDepthSort) {
  38738. if (distanceTo === undefined) {
  38739. distanceTo = BABYLON.Vector3.Zero();
  38740. }
  38741. var depthSortedFacets = options.depthSortedFacets;
  38742. }
  38743. }
  38744. // facetPartitioning reinit if needed
  38745. var xSubRatio = 0;
  38746. var ySubRatio = 0;
  38747. var zSubRatio = 0;
  38748. var subSq = 0;
  38749. if (computeFacetPartitioning && options && options.bbSize) {
  38750. var ox = 0; // X partitioning index for facet position
  38751. var oy = 0; // Y partinioning index for facet position
  38752. var oz = 0; // Z partinioning index for facet position
  38753. var b1x = 0; // X partitioning index for facet v1 vertex
  38754. var b1y = 0; // Y partitioning index for facet v1 vertex
  38755. var b1z = 0; // z partitioning index for facet v1 vertex
  38756. var b2x = 0; // X partitioning index for facet v2 vertex
  38757. var b2y = 0; // Y partitioning index for facet v2 vertex
  38758. var b2z = 0; // Z partitioning index for facet v2 vertex
  38759. var b3x = 0; // X partitioning index for facet v3 vertex
  38760. var b3y = 0; // Y partitioning index for facet v3 vertex
  38761. var b3z = 0; // Z partitioning index for facet v3 vertex
  38762. var block_idx_o = 0; // facet barycenter block index
  38763. var block_idx_v1 = 0; // v1 vertex block index
  38764. var block_idx_v2 = 0; // v2 vertex block index
  38765. var block_idx_v3 = 0; // v3 vertex block index
  38766. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38767. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38768. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38769. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38770. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38771. subSq = options.subDiv.max * options.subDiv.max;
  38772. options.facetPartitioning.length = 0;
  38773. }
  38774. // reset the normals
  38775. for (index = 0; index < positions.length; index++) {
  38776. normals[index] = 0.0;
  38777. }
  38778. // Loop : 1 indice triplet = 1 facet
  38779. var nbFaces = (indices.length / 3) | 0;
  38780. for (index = 0; index < nbFaces; index++) {
  38781. // get the indexes of the coordinates of each vertex of the facet
  38782. v1x = indices[index * 3] * 3;
  38783. v1y = v1x + 1;
  38784. v1z = v1x + 2;
  38785. v2x = indices[index * 3 + 1] * 3;
  38786. v2y = v2x + 1;
  38787. v2z = v2x + 2;
  38788. v3x = indices[index * 3 + 2] * 3;
  38789. v3y = v3x + 1;
  38790. v3z = v3x + 2;
  38791. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38792. p1p2y = positions[v1y] - positions[v2y];
  38793. p1p2z = positions[v1z] - positions[v2z];
  38794. p3p2x = positions[v3x] - positions[v2x];
  38795. p3p2y = positions[v3y] - positions[v2y];
  38796. p3p2z = positions[v3z] - positions[v2z];
  38797. // compute the face normal with the cross product
  38798. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38799. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38800. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38801. // normalize this normal and store it in the array facetData
  38802. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38803. length = (length === 0) ? 1.0 : length;
  38804. faceNormalx /= length;
  38805. faceNormaly /= length;
  38806. faceNormalz /= length;
  38807. if (computeFacetNormals && options) {
  38808. options.facetNormals[index].x = faceNormalx;
  38809. options.facetNormals[index].y = faceNormaly;
  38810. options.facetNormals[index].z = faceNormalz;
  38811. }
  38812. if (computeFacetPositions && options) {
  38813. // compute and the facet barycenter coordinates in the array facetPositions
  38814. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38815. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38816. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38817. }
  38818. if (computeFacetPartitioning && options) {
  38819. // store the facet indexes in arrays in the main facetPartitioning array :
  38820. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38821. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38822. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38823. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38824. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38825. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38826. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38827. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38828. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38829. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38830. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38831. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38832. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38833. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38834. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38835. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38836. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38837. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38838. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38839. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38840. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38841. // push each facet index in each block containing the vertex
  38842. options.facetPartitioning[block_idx_v1].push(index);
  38843. if (block_idx_v2 != block_idx_v1) {
  38844. options.facetPartitioning[block_idx_v2].push(index);
  38845. }
  38846. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38847. options.facetPartitioning[block_idx_v3].push(index);
  38848. }
  38849. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38850. options.facetPartitioning[block_idx_o].push(index);
  38851. }
  38852. }
  38853. if (computeDepthSort && options && options.facetPositions) {
  38854. var dsf = depthSortedFacets[index];
  38855. dsf.ind = index * 3;
  38856. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38857. }
  38858. // compute the normals anyway
  38859. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38860. normals[v1y] += faceNormaly;
  38861. normals[v1z] += faceNormalz;
  38862. normals[v2x] += faceNormalx;
  38863. normals[v2y] += faceNormaly;
  38864. normals[v2z] += faceNormalz;
  38865. normals[v3x] += faceNormalx;
  38866. normals[v3y] += faceNormaly;
  38867. normals[v3z] += faceNormalz;
  38868. }
  38869. // last normalization of each normal
  38870. for (index = 0; index < normals.length / 3; index++) {
  38871. faceNormalx = normals[index * 3];
  38872. faceNormaly = normals[index * 3 + 1];
  38873. faceNormalz = normals[index * 3 + 2];
  38874. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38875. length = (length === 0) ? 1.0 : length;
  38876. faceNormalx /= length;
  38877. faceNormaly /= length;
  38878. faceNormalz /= length;
  38879. normals[index * 3] = faceNormalx;
  38880. normals[index * 3 + 1] = faceNormaly;
  38881. normals[index * 3 + 2] = faceNormalz;
  38882. }
  38883. };
  38884. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38885. var li = indices.length;
  38886. var ln = normals.length;
  38887. var i;
  38888. var n;
  38889. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38890. switch (sideOrientation) {
  38891. case BABYLON.Mesh.FRONTSIDE:
  38892. // nothing changed
  38893. break;
  38894. case BABYLON.Mesh.BACKSIDE:
  38895. var tmp;
  38896. // indices
  38897. for (i = 0; i < li; i += 3) {
  38898. tmp = indices[i];
  38899. indices[i] = indices[i + 2];
  38900. indices[i + 2] = tmp;
  38901. }
  38902. // normals
  38903. for (n = 0; n < ln; n++) {
  38904. normals[n] = -normals[n];
  38905. }
  38906. break;
  38907. case BABYLON.Mesh.DOUBLESIDE:
  38908. // positions
  38909. var lp = positions.length;
  38910. var l = lp / 3;
  38911. for (var p = 0; p < lp; p++) {
  38912. positions[lp + p] = positions[p];
  38913. }
  38914. // indices
  38915. for (i = 0; i < li; i += 3) {
  38916. indices[i + li] = indices[i + 2] + l;
  38917. indices[i + 1 + li] = indices[i + 1] + l;
  38918. indices[i + 2 + li] = indices[i] + l;
  38919. }
  38920. // normals
  38921. for (n = 0; n < ln; n++) {
  38922. normals[ln + n] = -normals[n];
  38923. }
  38924. // uvs
  38925. var lu = uvs.length;
  38926. var u = 0;
  38927. for (u = 0; u < lu; u++) {
  38928. uvs[u + lu] = uvs[u];
  38929. }
  38930. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38931. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38932. u = 0;
  38933. for (i = 0; i < lu / 2; i++) {
  38934. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38935. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38936. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38937. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38938. u += 2;
  38939. }
  38940. break;
  38941. }
  38942. };
  38943. /**
  38944. * Applies VertexData created from the imported parameters to the geometry
  38945. * @param parsedVertexData the parsed data from an imported file
  38946. * @param geometry the geometry to apply the VertexData to
  38947. */
  38948. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38949. var vertexData = new VertexData();
  38950. // positions
  38951. var positions = parsedVertexData.positions;
  38952. if (positions) {
  38953. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38954. }
  38955. // normals
  38956. var normals = parsedVertexData.normals;
  38957. if (normals) {
  38958. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38959. }
  38960. // tangents
  38961. var tangents = parsedVertexData.tangents;
  38962. if (tangents) {
  38963. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38964. }
  38965. // uvs
  38966. var uvs = parsedVertexData.uvs;
  38967. if (uvs) {
  38968. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38969. }
  38970. // uv2s
  38971. var uv2s = parsedVertexData.uv2s;
  38972. if (uv2s) {
  38973. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38974. }
  38975. // uv3s
  38976. var uv3s = parsedVertexData.uv3s;
  38977. if (uv3s) {
  38978. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38979. }
  38980. // uv4s
  38981. var uv4s = parsedVertexData.uv4s;
  38982. if (uv4s) {
  38983. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38984. }
  38985. // uv5s
  38986. var uv5s = parsedVertexData.uv5s;
  38987. if (uv5s) {
  38988. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38989. }
  38990. // uv6s
  38991. var uv6s = parsedVertexData.uv6s;
  38992. if (uv6s) {
  38993. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38994. }
  38995. // colors
  38996. var colors = parsedVertexData.colors;
  38997. if (colors) {
  38998. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38999. }
  39000. // matricesIndices
  39001. var matricesIndices = parsedVertexData.matricesIndices;
  39002. if (matricesIndices) {
  39003. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39004. }
  39005. // matricesWeights
  39006. var matricesWeights = parsedVertexData.matricesWeights;
  39007. if (matricesWeights) {
  39008. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  39009. }
  39010. // indices
  39011. var indices = parsedVertexData.indices;
  39012. if (indices) {
  39013. vertexData.indices = indices;
  39014. }
  39015. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39016. };
  39017. return VertexData;
  39018. }());
  39019. BABYLON.VertexData = VertexData;
  39020. })(BABYLON || (BABYLON = {}));
  39021. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39022. var BABYLON;
  39023. (function (BABYLON) {
  39024. /**
  39025. * Class used to store geometry data (vertex buffers + index buffer)
  39026. */
  39027. var Geometry = /** @class */ (function () {
  39028. /**
  39029. * Creates a new geometry
  39030. * @param id defines the unique ID
  39031. * @param scene defines the hosting scene
  39032. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  39033. * @param updatable defines if geometry must be updatable (false by default)
  39034. * @param mesh defines the mesh that will be associated with the geometry
  39035. */
  39036. function Geometry(id, scene, vertexData, updatable, mesh) {
  39037. if (updatable === void 0) { updatable = false; }
  39038. if (mesh === void 0) { mesh = null; }
  39039. /**
  39040. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39041. */
  39042. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39043. this._totalVertices = 0;
  39044. this._isDisposed = false;
  39045. this._indexBufferIsUpdatable = false;
  39046. this.id = id;
  39047. this._engine = scene.getEngine();
  39048. this._meshes = [];
  39049. this._scene = scene;
  39050. //Init vertex buffer cache
  39051. this._vertexBuffers = {};
  39052. this._indices = [];
  39053. this._updatable = updatable;
  39054. // vertexData
  39055. if (vertexData) {
  39056. this.setAllVerticesData(vertexData, updatable);
  39057. }
  39058. else {
  39059. this._totalVertices = 0;
  39060. this._indices = [];
  39061. }
  39062. if (this._engine.getCaps().vertexArrayObject) {
  39063. this._vertexArrayObjects = {};
  39064. }
  39065. // applyToMesh
  39066. if (mesh) {
  39067. if (mesh.getClassName() === "LinesMesh") {
  39068. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39069. this._updateExtend();
  39070. }
  39071. this.applyToMesh(mesh);
  39072. mesh.computeWorldMatrix(true);
  39073. }
  39074. }
  39075. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39076. /**
  39077. * 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
  39078. */
  39079. get: function () {
  39080. return this._boundingBias;
  39081. },
  39082. /**
  39083. * 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
  39084. */
  39085. set: function (value) {
  39086. if (this._boundingBias && this._boundingBias.equals(value)) {
  39087. return;
  39088. }
  39089. this._boundingBias = value.clone();
  39090. this._updateBoundingInfo(true, null);
  39091. },
  39092. enumerable: true,
  39093. configurable: true
  39094. });
  39095. /**
  39096. * Static function used to attach a new empty geometry to a mesh
  39097. * @param mesh defines the mesh to attach the geometry to
  39098. * @returns the new {BABYLON.Geometry}
  39099. */
  39100. Geometry.CreateGeometryForMesh = function (mesh) {
  39101. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39102. geometry.applyToMesh(mesh);
  39103. return geometry;
  39104. };
  39105. Object.defineProperty(Geometry.prototype, "extend", {
  39106. /**
  39107. * Gets the current extend of the geometry
  39108. */
  39109. get: function () {
  39110. return this._extend;
  39111. },
  39112. enumerable: true,
  39113. configurable: true
  39114. });
  39115. /**
  39116. * Gets the hosting scene
  39117. * @returns the hosting {BABYLON.Scene}
  39118. */
  39119. Geometry.prototype.getScene = function () {
  39120. return this._scene;
  39121. };
  39122. /**
  39123. * Gets the hosting engine
  39124. * @returns the hosting {BABYLON.Engine}
  39125. */
  39126. Geometry.prototype.getEngine = function () {
  39127. return this._engine;
  39128. };
  39129. /**
  39130. * Defines if the geometry is ready to use
  39131. * @returns true if the geometry is ready to be used
  39132. */
  39133. Geometry.prototype.isReady = function () {
  39134. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39135. };
  39136. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39137. /**
  39138. * Gets a value indicating that the geometry should not be serialized
  39139. */
  39140. get: function () {
  39141. for (var index = 0; index < this._meshes.length; index++) {
  39142. if (!this._meshes[index].doNotSerialize) {
  39143. return false;
  39144. }
  39145. }
  39146. return true;
  39147. },
  39148. enumerable: true,
  39149. configurable: true
  39150. });
  39151. /** @hidden */
  39152. Geometry.prototype._rebuild = function () {
  39153. if (this._vertexArrayObjects) {
  39154. this._vertexArrayObjects = {};
  39155. }
  39156. // Index buffer
  39157. if (this._meshes.length !== 0 && this._indices) {
  39158. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39159. }
  39160. // Vertex buffers
  39161. for (var key in this._vertexBuffers) {
  39162. var vertexBuffer = this._vertexBuffers[key];
  39163. vertexBuffer._rebuild();
  39164. }
  39165. };
  39166. /**
  39167. * Affects all geometry data in one call
  39168. * @param vertexData defines the geometry data
  39169. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39170. */
  39171. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39172. vertexData.applyToGeometry(this, updatable);
  39173. this.notifyUpdate();
  39174. };
  39175. /**
  39176. * Set specific vertex data
  39177. * @param kind defines the data kind (Position, normal, etc...)
  39178. * @param data defines the vertex data to use
  39179. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39180. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39181. */
  39182. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39183. if (updatable === void 0) { updatable = false; }
  39184. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39185. this.setVerticesBuffer(buffer);
  39186. };
  39187. /**
  39188. * Removes a specific vertex data
  39189. * @param kind defines the data kind (Position, normal, etc...)
  39190. */
  39191. Geometry.prototype.removeVerticesData = function (kind) {
  39192. if (this._vertexBuffers[kind]) {
  39193. this._vertexBuffers[kind].dispose();
  39194. delete this._vertexBuffers[kind];
  39195. }
  39196. };
  39197. /**
  39198. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39199. * @param buffer defines the vertex buffer to use
  39200. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39201. */
  39202. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39203. if (totalVertices === void 0) { totalVertices = null; }
  39204. var kind = buffer.getKind();
  39205. if (this._vertexBuffers[kind]) {
  39206. this._vertexBuffers[kind].dispose();
  39207. }
  39208. this._vertexBuffers[kind] = buffer;
  39209. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39210. var data = buffer.getData();
  39211. if (totalVertices != null) {
  39212. this._totalVertices = totalVertices;
  39213. }
  39214. else {
  39215. if (data != null) {
  39216. this._totalVertices = data.length / (buffer.byteStride / 4);
  39217. }
  39218. }
  39219. this._updateExtend(data);
  39220. this._resetPointsArrayCache();
  39221. var meshes = this._meshes;
  39222. var numOfMeshes = meshes.length;
  39223. for (var index = 0; index < numOfMeshes; index++) {
  39224. var mesh = meshes[index];
  39225. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39226. mesh._createGlobalSubMesh(false);
  39227. mesh.computeWorldMatrix(true);
  39228. }
  39229. }
  39230. this.notifyUpdate(kind);
  39231. if (this._vertexArrayObjects) {
  39232. this._disposeVertexArrayObjects();
  39233. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39234. }
  39235. };
  39236. /**
  39237. * Update a specific vertex buffer
  39238. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39239. * It will do nothing if the buffer is not updatable
  39240. * @param kind defines the data kind (Position, normal, etc...)
  39241. * @param data defines the data to use
  39242. * @param offset defines the offset in the target buffer where to store the data
  39243. * @param useBytes set to true if the offset is in bytes
  39244. */
  39245. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39246. if (useBytes === void 0) { useBytes = false; }
  39247. var vertexBuffer = this.getVertexBuffer(kind);
  39248. if (!vertexBuffer) {
  39249. return;
  39250. }
  39251. vertexBuffer.updateDirectly(data, offset, useBytes);
  39252. this.notifyUpdate(kind);
  39253. };
  39254. /**
  39255. * Update a specific vertex buffer
  39256. * This function will create a new buffer if the current one is not updatable
  39257. * @param kind defines the data kind (Position, normal, etc...)
  39258. * @param data defines the data to use
  39259. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39260. */
  39261. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39262. if (updateExtends === void 0) { updateExtends = false; }
  39263. var vertexBuffer = this.getVertexBuffer(kind);
  39264. if (!vertexBuffer) {
  39265. return;
  39266. }
  39267. vertexBuffer.update(data);
  39268. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39269. this._updateBoundingInfo(updateExtends, data);
  39270. }
  39271. this.notifyUpdate(kind);
  39272. };
  39273. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39274. if (updateExtends) {
  39275. this._updateExtend(data);
  39276. }
  39277. var meshes = this._meshes;
  39278. var numOfMeshes = meshes.length;
  39279. this._resetPointsArrayCache();
  39280. for (var index = 0; index < numOfMeshes; index++) {
  39281. var mesh = meshes[index];
  39282. if (updateExtends) {
  39283. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39284. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39285. var subMesh = mesh.subMeshes[subIndex];
  39286. subMesh.refreshBoundingInfo();
  39287. }
  39288. }
  39289. }
  39290. };
  39291. /** @hidden */
  39292. Geometry.prototype._bind = function (effect, indexToBind) {
  39293. if (!effect) {
  39294. return;
  39295. }
  39296. if (indexToBind === undefined) {
  39297. indexToBind = this._indexBuffer;
  39298. }
  39299. var vbs = this.getVertexBuffers();
  39300. if (!vbs) {
  39301. return;
  39302. }
  39303. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39304. this._engine.bindBuffers(vbs, indexToBind, effect);
  39305. return;
  39306. }
  39307. // Using VAO
  39308. if (!this._vertexArrayObjects[effect.key]) {
  39309. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39310. }
  39311. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39312. };
  39313. /**
  39314. * Gets total number of vertices
  39315. * @returns the total number of vertices
  39316. */
  39317. Geometry.prototype.getTotalVertices = function () {
  39318. if (!this.isReady()) {
  39319. return 0;
  39320. }
  39321. return this._totalVertices;
  39322. };
  39323. /**
  39324. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39325. * @param kind defines the data kind (Position, normal, etc...)
  39326. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39327. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39328. * @returns a float array containing vertex data
  39329. */
  39330. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39331. var vertexBuffer = this.getVertexBuffer(kind);
  39332. if (!vertexBuffer) {
  39333. return null;
  39334. }
  39335. var data = vertexBuffer.getData();
  39336. if (!data) {
  39337. return null;
  39338. }
  39339. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39340. var count = this._totalVertices * vertexBuffer.getSize();
  39341. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39342. var copy_1 = new Array(count);
  39343. vertexBuffer.forEach(count, function (value, index) {
  39344. copy_1[index] = value;
  39345. });
  39346. return copy_1;
  39347. }
  39348. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39349. if (data instanceof Array) {
  39350. var offset = vertexBuffer.byteOffset / 4;
  39351. return BABYLON.Tools.Slice(data, offset, offset + count);
  39352. }
  39353. else if (data instanceof ArrayBuffer) {
  39354. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39355. }
  39356. else {
  39357. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39358. }
  39359. }
  39360. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39361. return BABYLON.Tools.Slice(data);
  39362. }
  39363. return data;
  39364. };
  39365. /**
  39366. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39367. * @param kind defines the data kind (Position, normal, etc...)
  39368. * @returns true if the vertex buffer with the specified kind is updatable
  39369. */
  39370. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39371. var vb = this._vertexBuffers[kind];
  39372. if (!vb) {
  39373. return false;
  39374. }
  39375. return vb.isUpdatable();
  39376. };
  39377. /**
  39378. * Gets a specific vertex buffer
  39379. * @param kind defines the data kind (Position, normal, etc...)
  39380. * @returns a {BABYLON.VertexBuffer}
  39381. */
  39382. Geometry.prototype.getVertexBuffer = function (kind) {
  39383. if (!this.isReady()) {
  39384. return null;
  39385. }
  39386. return this._vertexBuffers[kind];
  39387. };
  39388. /**
  39389. * Returns all vertex buffers
  39390. * @return an object holding all vertex buffers indexed by kind
  39391. */
  39392. Geometry.prototype.getVertexBuffers = function () {
  39393. if (!this.isReady()) {
  39394. return null;
  39395. }
  39396. return this._vertexBuffers;
  39397. };
  39398. /**
  39399. * Gets a boolean indicating if specific vertex buffer is present
  39400. * @param kind defines the data kind (Position, normal, etc...)
  39401. * @returns true if data is present
  39402. */
  39403. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39404. if (!this._vertexBuffers) {
  39405. if (this._delayInfo) {
  39406. return this._delayInfo.indexOf(kind) !== -1;
  39407. }
  39408. return false;
  39409. }
  39410. return this._vertexBuffers[kind] !== undefined;
  39411. };
  39412. /**
  39413. * Gets a list of all attached data kinds (Position, normal, etc...)
  39414. * @returns a list of string containing all kinds
  39415. */
  39416. Geometry.prototype.getVerticesDataKinds = function () {
  39417. var result = [];
  39418. var kind;
  39419. if (!this._vertexBuffers && this._delayInfo) {
  39420. for (kind in this._delayInfo) {
  39421. result.push(kind);
  39422. }
  39423. }
  39424. else {
  39425. for (kind in this._vertexBuffers) {
  39426. result.push(kind);
  39427. }
  39428. }
  39429. return result;
  39430. };
  39431. /**
  39432. * Update index buffer
  39433. * @param indices defines the indices to store in the index buffer
  39434. * @param offset defines the offset in the target buffer where to store the data
  39435. */
  39436. Geometry.prototype.updateIndices = function (indices, offset) {
  39437. if (!this._indexBuffer) {
  39438. return;
  39439. }
  39440. if (!this._indexBufferIsUpdatable) {
  39441. this.setIndices(indices, null, true);
  39442. }
  39443. else {
  39444. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39445. }
  39446. };
  39447. /**
  39448. * Creates a new index buffer
  39449. * @param indices defines the indices to store in the index buffer
  39450. * @param totalVertices defines the total number of vertices (could be null)
  39451. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39452. */
  39453. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39454. if (totalVertices === void 0) { totalVertices = null; }
  39455. if (updatable === void 0) { updatable = false; }
  39456. if (this._indexBuffer) {
  39457. this._engine._releaseBuffer(this._indexBuffer);
  39458. }
  39459. this._disposeVertexArrayObjects();
  39460. this._indices = indices;
  39461. this._indexBufferIsUpdatable = updatable;
  39462. if (this._meshes.length !== 0 && this._indices) {
  39463. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39464. }
  39465. if (totalVertices != undefined) { // including null and undefined
  39466. this._totalVertices = totalVertices;
  39467. }
  39468. var meshes = this._meshes;
  39469. var numOfMeshes = meshes.length;
  39470. for (var index = 0; index < numOfMeshes; index++) {
  39471. meshes[index]._createGlobalSubMesh(true);
  39472. }
  39473. this.notifyUpdate();
  39474. };
  39475. /**
  39476. * Return the total number of indices
  39477. * @returns the total number of indices
  39478. */
  39479. Geometry.prototype.getTotalIndices = function () {
  39480. if (!this.isReady()) {
  39481. return 0;
  39482. }
  39483. return this._indices.length;
  39484. };
  39485. /**
  39486. * Gets the index buffer array
  39487. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39488. * @returns the index buffer array
  39489. */
  39490. Geometry.prototype.getIndices = function (copyWhenShared) {
  39491. if (!this.isReady()) {
  39492. return null;
  39493. }
  39494. var orig = this._indices;
  39495. if (!copyWhenShared || this._meshes.length === 1) {
  39496. return orig;
  39497. }
  39498. else {
  39499. var len = orig.length;
  39500. var copy = [];
  39501. for (var i = 0; i < len; i++) {
  39502. copy.push(orig[i]);
  39503. }
  39504. return copy;
  39505. }
  39506. };
  39507. /**
  39508. * Gets the index buffer
  39509. * @return the index buffer
  39510. */
  39511. Geometry.prototype.getIndexBuffer = function () {
  39512. if (!this.isReady()) {
  39513. return null;
  39514. }
  39515. return this._indexBuffer;
  39516. };
  39517. /** @hidden */
  39518. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39519. if (effect === void 0) { effect = null; }
  39520. if (!effect || !this._vertexArrayObjects) {
  39521. return;
  39522. }
  39523. if (this._vertexArrayObjects[effect.key]) {
  39524. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39525. delete this._vertexArrayObjects[effect.key];
  39526. }
  39527. };
  39528. /**
  39529. * Release the associated resources for a specific mesh
  39530. * @param mesh defines the source mesh
  39531. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39532. */
  39533. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39534. var meshes = this._meshes;
  39535. var index = meshes.indexOf(mesh);
  39536. if (index === -1) {
  39537. return;
  39538. }
  39539. meshes.splice(index, 1);
  39540. mesh._geometry = null;
  39541. if (meshes.length === 0 && shouldDispose) {
  39542. this.dispose();
  39543. }
  39544. };
  39545. /**
  39546. * Apply current geometry to a given mesh
  39547. * @param mesh defines the mesh to apply geometry to
  39548. */
  39549. Geometry.prototype.applyToMesh = function (mesh) {
  39550. if (mesh._geometry === this) {
  39551. return;
  39552. }
  39553. var previousGeometry = mesh._geometry;
  39554. if (previousGeometry) {
  39555. previousGeometry.releaseForMesh(mesh);
  39556. }
  39557. var meshes = this._meshes;
  39558. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39559. mesh._geometry = this;
  39560. this._scene.pushGeometry(this);
  39561. meshes.push(mesh);
  39562. if (this.isReady()) {
  39563. this._applyToMesh(mesh);
  39564. }
  39565. else {
  39566. mesh._boundingInfo = this._boundingInfo;
  39567. }
  39568. };
  39569. Geometry.prototype._updateExtend = function (data) {
  39570. if (data === void 0) { data = null; }
  39571. if (!data) {
  39572. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39573. }
  39574. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39575. };
  39576. Geometry.prototype._applyToMesh = function (mesh) {
  39577. var numOfMeshes = this._meshes.length;
  39578. // vertexBuffers
  39579. for (var kind in this._vertexBuffers) {
  39580. if (numOfMeshes === 1) {
  39581. this._vertexBuffers[kind].create();
  39582. }
  39583. var buffer = this._vertexBuffers[kind].getBuffer();
  39584. if (buffer)
  39585. buffer.references = numOfMeshes;
  39586. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39587. if (!this._extend) {
  39588. this._updateExtend();
  39589. }
  39590. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39591. mesh._createGlobalSubMesh(false);
  39592. //bounding info was just created again, world matrix should be applied again.
  39593. mesh._updateBoundingInfo();
  39594. }
  39595. }
  39596. // indexBuffer
  39597. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39598. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39599. }
  39600. if (this._indexBuffer) {
  39601. this._indexBuffer.references = numOfMeshes;
  39602. }
  39603. };
  39604. Geometry.prototype.notifyUpdate = function (kind) {
  39605. if (this.onGeometryUpdated) {
  39606. this.onGeometryUpdated(this, kind);
  39607. }
  39608. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39609. var mesh = _a[_i];
  39610. mesh._markSubMeshesAsAttributesDirty();
  39611. }
  39612. };
  39613. /**
  39614. * Load the geometry if it was flagged as delay loaded
  39615. * @param scene defines the hosting scene
  39616. * @param onLoaded defines a callback called when the geometry is loaded
  39617. */
  39618. Geometry.prototype.load = function (scene, onLoaded) {
  39619. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39620. return;
  39621. }
  39622. if (this.isReady()) {
  39623. if (onLoaded) {
  39624. onLoaded();
  39625. }
  39626. return;
  39627. }
  39628. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39629. this._queueLoad(scene, onLoaded);
  39630. };
  39631. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39632. var _this = this;
  39633. if (!this.delayLoadingFile) {
  39634. return;
  39635. }
  39636. scene._addPendingData(this);
  39637. scene._loadFile(this.delayLoadingFile, function (data) {
  39638. if (!_this._delayLoadingFunction) {
  39639. return;
  39640. }
  39641. _this._delayLoadingFunction(JSON.parse(data), _this);
  39642. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39643. _this._delayInfo = [];
  39644. scene._removePendingData(_this);
  39645. var meshes = _this._meshes;
  39646. var numOfMeshes = meshes.length;
  39647. for (var index = 0; index < numOfMeshes; index++) {
  39648. _this._applyToMesh(meshes[index]);
  39649. }
  39650. if (onLoaded) {
  39651. onLoaded();
  39652. }
  39653. }, undefined, true);
  39654. };
  39655. /**
  39656. * Invert the geometry to move from a right handed system to a left handed one.
  39657. */
  39658. Geometry.prototype.toLeftHanded = function () {
  39659. // Flip faces
  39660. var tIndices = this.getIndices(false);
  39661. if (tIndices != null && tIndices.length > 0) {
  39662. for (var i = 0; i < tIndices.length; i += 3) {
  39663. var tTemp = tIndices[i + 0];
  39664. tIndices[i + 0] = tIndices[i + 2];
  39665. tIndices[i + 2] = tTemp;
  39666. }
  39667. this.setIndices(tIndices);
  39668. }
  39669. // Negate position.z
  39670. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39671. if (tPositions != null && tPositions.length > 0) {
  39672. for (var i = 0; i < tPositions.length; i += 3) {
  39673. tPositions[i + 2] = -tPositions[i + 2];
  39674. }
  39675. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39676. }
  39677. // Negate normal.z
  39678. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39679. if (tNormals != null && tNormals.length > 0) {
  39680. for (var i = 0; i < tNormals.length; i += 3) {
  39681. tNormals[i + 2] = -tNormals[i + 2];
  39682. }
  39683. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39684. }
  39685. };
  39686. // Cache
  39687. /** @hidden */
  39688. Geometry.prototype._resetPointsArrayCache = function () {
  39689. this._positions = null;
  39690. };
  39691. /** @hidden */
  39692. Geometry.prototype._generatePointsArray = function () {
  39693. if (this._positions)
  39694. return true;
  39695. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39696. if (!data || data.length === 0) {
  39697. return false;
  39698. }
  39699. this._positions = [];
  39700. for (var index = 0; index < data.length; index += 3) {
  39701. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39702. }
  39703. return true;
  39704. };
  39705. /**
  39706. * Gets a value indicating if the geometry is disposed
  39707. * @returns true if the geometry was disposed
  39708. */
  39709. Geometry.prototype.isDisposed = function () {
  39710. return this._isDisposed;
  39711. };
  39712. Geometry.prototype._disposeVertexArrayObjects = function () {
  39713. if (this._vertexArrayObjects) {
  39714. for (var kind in this._vertexArrayObjects) {
  39715. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39716. }
  39717. this._vertexArrayObjects = {};
  39718. }
  39719. };
  39720. /**
  39721. * Free all associated resources
  39722. */
  39723. Geometry.prototype.dispose = function () {
  39724. var meshes = this._meshes;
  39725. var numOfMeshes = meshes.length;
  39726. var index;
  39727. for (index = 0; index < numOfMeshes; index++) {
  39728. this.releaseForMesh(meshes[index]);
  39729. }
  39730. this._meshes = [];
  39731. this._disposeVertexArrayObjects();
  39732. for (var kind in this._vertexBuffers) {
  39733. this._vertexBuffers[kind].dispose();
  39734. }
  39735. this._vertexBuffers = {};
  39736. this._totalVertices = 0;
  39737. if (this._indexBuffer) {
  39738. this._engine._releaseBuffer(this._indexBuffer);
  39739. }
  39740. this._indexBuffer = null;
  39741. this._indices = [];
  39742. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39743. this.delayLoadingFile = null;
  39744. this._delayLoadingFunction = null;
  39745. this._delayInfo = [];
  39746. this._boundingInfo = null;
  39747. this._scene.removeGeometry(this);
  39748. this._isDisposed = true;
  39749. };
  39750. /**
  39751. * Clone the current geometry into a new geometry
  39752. * @param id defines the unique ID of the new geometry
  39753. * @returns a new geometry object
  39754. */
  39755. Geometry.prototype.copy = function (id) {
  39756. var vertexData = new BABYLON.VertexData();
  39757. vertexData.indices = [];
  39758. var indices = this.getIndices();
  39759. if (indices) {
  39760. for (var index = 0; index < indices.length; index++) {
  39761. vertexData.indices.push(indices[index]);
  39762. }
  39763. }
  39764. var updatable = false;
  39765. var stopChecking = false;
  39766. var kind;
  39767. for (kind in this._vertexBuffers) {
  39768. // using slice() to make a copy of the array and not just reference it
  39769. var data = this.getVerticesData(kind);
  39770. if (data instanceof Float32Array) {
  39771. vertexData.set(new Float32Array(data), kind);
  39772. }
  39773. else {
  39774. vertexData.set(data.slice(0), kind);
  39775. }
  39776. if (!stopChecking) {
  39777. var vb = this.getVertexBuffer(kind);
  39778. if (vb) {
  39779. updatable = vb.isUpdatable();
  39780. stopChecking = !updatable;
  39781. }
  39782. }
  39783. }
  39784. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39785. geometry.delayLoadState = this.delayLoadState;
  39786. geometry.delayLoadingFile = this.delayLoadingFile;
  39787. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39788. for (kind in this._delayInfo) {
  39789. geometry._delayInfo = geometry._delayInfo || [];
  39790. geometry._delayInfo.push(kind);
  39791. }
  39792. // Bounding info
  39793. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39794. return geometry;
  39795. };
  39796. /**
  39797. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39798. * @return a JSON representation of the current geometry data (without the vertices data)
  39799. */
  39800. Geometry.prototype.serialize = function () {
  39801. var serializationObject = {};
  39802. serializationObject.id = this.id;
  39803. serializationObject.updatable = this._updatable;
  39804. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39805. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39806. }
  39807. return serializationObject;
  39808. };
  39809. Geometry.prototype.toNumberArray = function (origin) {
  39810. if (Array.isArray(origin)) {
  39811. return origin;
  39812. }
  39813. else {
  39814. return Array.prototype.slice.call(origin);
  39815. }
  39816. };
  39817. /**
  39818. * Serialize all vertices data into a JSON oject
  39819. * @returns a JSON representation of the current geometry data
  39820. */
  39821. Geometry.prototype.serializeVerticeData = function () {
  39822. var serializationObject = this.serialize();
  39823. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39824. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39825. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39826. serializationObject.positions._updatable = true;
  39827. }
  39828. }
  39829. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39830. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39831. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39832. serializationObject.normals._updatable = true;
  39833. }
  39834. }
  39835. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39836. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39837. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39838. serializationObject.tangets._updatable = true;
  39839. }
  39840. }
  39841. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39842. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39843. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39844. serializationObject.uvs._updatable = true;
  39845. }
  39846. }
  39847. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39848. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39849. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39850. serializationObject.uv2s._updatable = true;
  39851. }
  39852. }
  39853. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39854. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39855. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39856. serializationObject.uv3s._updatable = true;
  39857. }
  39858. }
  39859. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39860. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39861. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39862. serializationObject.uv4s._updatable = true;
  39863. }
  39864. }
  39865. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39866. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39867. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39868. serializationObject.uv5s._updatable = true;
  39869. }
  39870. }
  39871. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39872. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39873. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39874. serializationObject.uv6s._updatable = true;
  39875. }
  39876. }
  39877. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39878. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39879. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39880. serializationObject.colors._updatable = true;
  39881. }
  39882. }
  39883. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39884. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39885. serializationObject.matricesIndices._isExpanded = true;
  39886. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39887. serializationObject.matricesIndices._updatable = true;
  39888. }
  39889. }
  39890. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39891. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39892. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39893. serializationObject.matricesWeights._updatable = true;
  39894. }
  39895. }
  39896. serializationObject.indices = this.toNumberArray(this.getIndices());
  39897. return serializationObject;
  39898. };
  39899. // Statics
  39900. /**
  39901. * Extracts a clone of a mesh geometry
  39902. * @param mesh defines the source mesh
  39903. * @param id defines the unique ID of the new geometry object
  39904. * @returns the new geometry object
  39905. */
  39906. Geometry.ExtractFromMesh = function (mesh, id) {
  39907. var geometry = mesh._geometry;
  39908. if (!geometry) {
  39909. return null;
  39910. }
  39911. return geometry.copy(id);
  39912. };
  39913. /**
  39914. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39915. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39916. * Be aware Math.random() could cause collisions, but:
  39917. * "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"
  39918. * @returns a string containing a new GUID
  39919. */
  39920. Geometry.RandomId = function () {
  39921. return BABYLON.Tools.RandomId();
  39922. };
  39923. /** @hidden */
  39924. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39925. var scene = mesh.getScene();
  39926. // Geometry
  39927. var geometryId = parsedGeometry.geometryId;
  39928. if (geometryId) {
  39929. var geometry = scene.getGeometryByID(geometryId);
  39930. if (geometry) {
  39931. geometry.applyToMesh(mesh);
  39932. }
  39933. }
  39934. else if (parsedGeometry instanceof ArrayBuffer) {
  39935. var binaryInfo = mesh._binaryInfo;
  39936. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39937. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39938. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39939. }
  39940. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39941. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39942. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39943. }
  39944. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39945. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39946. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39947. }
  39948. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39949. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39950. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39951. }
  39952. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39953. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39954. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39955. }
  39956. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39957. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39958. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39959. }
  39960. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39961. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39962. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39963. }
  39964. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39965. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39966. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39967. }
  39968. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39969. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39970. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39971. }
  39972. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39973. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39974. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39975. }
  39976. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39977. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39978. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39979. }
  39980. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39981. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39982. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39983. }
  39984. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39985. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39986. mesh.setIndices(indicesData, null);
  39987. }
  39988. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39989. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39990. mesh.subMeshes = [];
  39991. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39992. var materialIndex = subMeshesData[(i * 5) + 0];
  39993. var verticesStart = subMeshesData[(i * 5) + 1];
  39994. var verticesCount = subMeshesData[(i * 5) + 2];
  39995. var indexStart = subMeshesData[(i * 5) + 3];
  39996. var indexCount = subMeshesData[(i * 5) + 4];
  39997. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39998. }
  39999. }
  40000. }
  40001. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40002. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40003. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40004. if (parsedGeometry.tangents) {
  40005. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  40006. }
  40007. if (parsedGeometry.uvs) {
  40008. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40009. }
  40010. if (parsedGeometry.uvs2) {
  40011. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40012. }
  40013. if (parsedGeometry.uvs3) {
  40014. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40015. }
  40016. if (parsedGeometry.uvs4) {
  40017. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40018. }
  40019. if (parsedGeometry.uvs5) {
  40020. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40021. }
  40022. if (parsedGeometry.uvs6) {
  40023. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40024. }
  40025. if (parsedGeometry.colors) {
  40026. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40027. }
  40028. if (parsedGeometry.matricesIndices) {
  40029. if (!parsedGeometry.matricesIndices._isExpanded) {
  40030. var floatIndices = [];
  40031. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40032. var matricesIndex = parsedGeometry.matricesIndices[i];
  40033. floatIndices.push(matricesIndex & 0x000000FF);
  40034. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40035. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40036. floatIndices.push(matricesIndex >> 24);
  40037. }
  40038. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40039. }
  40040. else {
  40041. delete parsedGeometry.matricesIndices._isExpanded;
  40042. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40043. }
  40044. }
  40045. if (parsedGeometry.matricesIndicesExtra) {
  40046. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40047. var floatIndices = [];
  40048. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40049. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40050. floatIndices.push(matricesIndex & 0x000000FF);
  40051. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40052. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40053. floatIndices.push(matricesIndex >> 24);
  40054. }
  40055. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40056. }
  40057. else {
  40058. delete parsedGeometry.matricesIndices._isExpanded;
  40059. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40060. }
  40061. }
  40062. if (parsedGeometry.matricesWeights) {
  40063. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40064. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40065. }
  40066. if (parsedGeometry.matricesWeightsExtra) {
  40067. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40068. }
  40069. mesh.setIndices(parsedGeometry.indices, null);
  40070. }
  40071. // SubMeshes
  40072. if (parsedGeometry.subMeshes) {
  40073. mesh.subMeshes = [];
  40074. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40075. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40076. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40077. }
  40078. }
  40079. // Flat shading
  40080. if (mesh._shouldGenerateFlatShading) {
  40081. mesh.convertToFlatShadedMesh();
  40082. delete mesh._shouldGenerateFlatShading;
  40083. }
  40084. // Update
  40085. mesh.computeWorldMatrix(true);
  40086. // Octree
  40087. var sceneOctree = scene.selectionOctree;
  40088. if (sceneOctree !== undefined && sceneOctree !== null) {
  40089. sceneOctree.addMesh(mesh);
  40090. }
  40091. };
  40092. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40093. var epsilon = 1e-3;
  40094. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40095. return;
  40096. }
  40097. var noInfluenceBoneIndex = 0.0;
  40098. if (parsedGeometry.skeletonId > -1) {
  40099. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40100. if (!skeleton) {
  40101. return;
  40102. }
  40103. noInfluenceBoneIndex = skeleton.bones.length;
  40104. }
  40105. else {
  40106. return;
  40107. }
  40108. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40109. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40110. var matricesWeights = parsedGeometry.matricesWeights;
  40111. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40112. var influencers = parsedGeometry.numBoneInfluencer;
  40113. var size = matricesWeights.length;
  40114. for (var i = 0; i < size; i += 4) {
  40115. var weight = 0.0;
  40116. var firstZeroWeight = -1;
  40117. for (var j = 0; j < 4; j++) {
  40118. var w = matricesWeights[i + j];
  40119. weight += w;
  40120. if (w < epsilon && firstZeroWeight < 0) {
  40121. firstZeroWeight = j;
  40122. }
  40123. }
  40124. if (matricesWeightsExtra) {
  40125. for (var j = 0; j < 4; j++) {
  40126. var w = matricesWeightsExtra[i + j];
  40127. weight += w;
  40128. if (w < epsilon && firstZeroWeight < 0) {
  40129. firstZeroWeight = j + 4;
  40130. }
  40131. }
  40132. }
  40133. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40134. firstZeroWeight = influencers - 1;
  40135. }
  40136. if (weight > epsilon) {
  40137. var mweight = 1.0 / weight;
  40138. for (var j = 0; j < 4; j++) {
  40139. matricesWeights[i + j] *= mweight;
  40140. }
  40141. if (matricesWeightsExtra) {
  40142. for (var j = 0; j < 4; j++) {
  40143. matricesWeightsExtra[i + j] *= mweight;
  40144. }
  40145. }
  40146. }
  40147. else {
  40148. if (firstZeroWeight >= 4) {
  40149. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40150. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40151. }
  40152. else {
  40153. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40154. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40155. }
  40156. }
  40157. }
  40158. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40159. if (parsedGeometry.matricesWeightsExtra) {
  40160. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40161. }
  40162. };
  40163. /**
  40164. * Create a new geometry from persisted data (Using .babylon file format)
  40165. * @param parsedVertexData defines the persisted data
  40166. * @param scene defines the hosting scene
  40167. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40168. * @returns the new geometry object
  40169. */
  40170. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40171. if (scene.getGeometryByID(parsedVertexData.id)) {
  40172. return null; // null since geometry could be something else than a box...
  40173. }
  40174. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40175. if (BABYLON.Tags) {
  40176. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40177. }
  40178. if (parsedVertexData.delayLoadingFile) {
  40179. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40180. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40181. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40182. geometry._delayInfo = [];
  40183. if (parsedVertexData.hasUVs) {
  40184. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40185. }
  40186. if (parsedVertexData.hasUVs2) {
  40187. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40188. }
  40189. if (parsedVertexData.hasUVs3) {
  40190. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40191. }
  40192. if (parsedVertexData.hasUVs4) {
  40193. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40194. }
  40195. if (parsedVertexData.hasUVs5) {
  40196. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40197. }
  40198. if (parsedVertexData.hasUVs6) {
  40199. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40200. }
  40201. if (parsedVertexData.hasColors) {
  40202. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40203. }
  40204. if (parsedVertexData.hasMatricesIndices) {
  40205. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40206. }
  40207. if (parsedVertexData.hasMatricesWeights) {
  40208. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40209. }
  40210. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40211. }
  40212. else {
  40213. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40214. }
  40215. scene.pushGeometry(geometry, true);
  40216. return geometry;
  40217. };
  40218. return Geometry;
  40219. }());
  40220. BABYLON.Geometry = Geometry;
  40221. // Primitives
  40222. /// Abstract class
  40223. /**
  40224. * Abstract class used to provide common services for all typed geometries
  40225. * @hidden
  40226. */
  40227. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40228. __extends(_PrimitiveGeometry, _super);
  40229. /**
  40230. * Creates a new typed geometry
  40231. * @param id defines the unique ID of the geometry
  40232. * @param scene defines the hosting scene
  40233. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40234. * @param mesh defines the hosting mesh (can be null)
  40235. */
  40236. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40237. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40238. if (mesh === void 0) { mesh = null; }
  40239. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40240. _this._canBeRegenerated = _canBeRegenerated;
  40241. _this._beingRegenerated = true;
  40242. _this.regenerate();
  40243. _this._beingRegenerated = false;
  40244. return _this;
  40245. }
  40246. /**
  40247. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40248. * @returns true if the geometry can be regenerated
  40249. */
  40250. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40251. return this._canBeRegenerated;
  40252. };
  40253. /**
  40254. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40255. */
  40256. _PrimitiveGeometry.prototype.regenerate = function () {
  40257. if (!this._canBeRegenerated) {
  40258. return;
  40259. }
  40260. this._beingRegenerated = true;
  40261. this.setAllVerticesData(this._regenerateVertexData(), false);
  40262. this._beingRegenerated = false;
  40263. };
  40264. /**
  40265. * Clone the geometry
  40266. * @param id defines the unique ID of the new geometry
  40267. * @returns the new geometry
  40268. */
  40269. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40270. return _super.prototype.copy.call(this, id);
  40271. };
  40272. // overrides
  40273. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40274. if (!this._beingRegenerated) {
  40275. return;
  40276. }
  40277. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40278. };
  40279. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40280. if (!this._beingRegenerated) {
  40281. return;
  40282. }
  40283. _super.prototype.setVerticesData.call(this, kind, data, false);
  40284. };
  40285. // to override
  40286. /** @hidden */
  40287. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40288. throw new Error("Abstract method");
  40289. };
  40290. _PrimitiveGeometry.prototype.copy = function (id) {
  40291. throw new Error("Must be overriden in sub-classes.");
  40292. };
  40293. _PrimitiveGeometry.prototype.serialize = function () {
  40294. var serializationObject = _super.prototype.serialize.call(this);
  40295. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40296. return serializationObject;
  40297. };
  40298. return _PrimitiveGeometry;
  40299. }(Geometry));
  40300. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40301. /**
  40302. * Creates a ribbon geometry
  40303. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40304. */
  40305. var RibbonGeometry = /** @class */ (function (_super) {
  40306. __extends(RibbonGeometry, _super);
  40307. /**
  40308. * Creates a ribbon geometry
  40309. * @param id defines the unique ID of the geometry
  40310. * @param scene defines the hosting scene
  40311. * @param pathArray defines the array of paths to use
  40312. * @param closeArray defines if the last path and the first path must be joined
  40313. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40314. * @param offset defines the offset between points
  40315. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40316. * @param mesh defines the hosting mesh (can be null)
  40317. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40318. */
  40319. function RibbonGeometry(id, scene,
  40320. /**
  40321. * Defines the array of paths to use
  40322. */
  40323. pathArray,
  40324. /**
  40325. * Defines if the last and first points of each path in your pathArray must be joined
  40326. */
  40327. closeArray,
  40328. /**
  40329. * Defines if the last and first points of each path in your pathArray must be joined
  40330. */
  40331. closePath,
  40332. /**
  40333. * Defines the offset between points
  40334. */
  40335. offset, canBeRegenerated, mesh,
  40336. /**
  40337. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40338. */
  40339. side) {
  40340. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40341. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40342. _this.pathArray = pathArray;
  40343. _this.closeArray = closeArray;
  40344. _this.closePath = closePath;
  40345. _this.offset = offset;
  40346. _this.side = side;
  40347. return _this;
  40348. }
  40349. /** @hidden */
  40350. RibbonGeometry.prototype._regenerateVertexData = function () {
  40351. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40352. };
  40353. RibbonGeometry.prototype.copy = function (id) {
  40354. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40355. };
  40356. return RibbonGeometry;
  40357. }(_PrimitiveGeometry));
  40358. BABYLON.RibbonGeometry = RibbonGeometry;
  40359. /**
  40360. * Creates a box geometry
  40361. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40362. */
  40363. var BoxGeometry = /** @class */ (function (_super) {
  40364. __extends(BoxGeometry, _super);
  40365. /**
  40366. * Creates a box geometry
  40367. * @param id defines the unique ID of the geometry
  40368. * @param scene defines the hosting scene
  40369. * @param size defines the zise of the box (width, height and depth are the same)
  40370. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40371. * @param mesh defines the hosting mesh (can be null)
  40372. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40373. */
  40374. function BoxGeometry(id, scene,
  40375. /**
  40376. * Defines the zise of the box (width, height and depth are the same)
  40377. */
  40378. size, canBeRegenerated, mesh,
  40379. /**
  40380. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40381. */
  40382. side) {
  40383. if (mesh === void 0) { mesh = null; }
  40384. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40385. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40386. _this.size = size;
  40387. _this.side = side;
  40388. return _this;
  40389. }
  40390. BoxGeometry.prototype._regenerateVertexData = function () {
  40391. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40392. };
  40393. BoxGeometry.prototype.copy = function (id) {
  40394. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40395. };
  40396. BoxGeometry.prototype.serialize = function () {
  40397. var serializationObject = _super.prototype.serialize.call(this);
  40398. serializationObject.size = this.size;
  40399. return serializationObject;
  40400. };
  40401. BoxGeometry.Parse = function (parsedBox, scene) {
  40402. if (scene.getGeometryByID(parsedBox.id)) {
  40403. return null; // null since geometry could be something else than a box...
  40404. }
  40405. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40406. if (BABYLON.Tags) {
  40407. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40408. }
  40409. scene.pushGeometry(box, true);
  40410. return box;
  40411. };
  40412. return BoxGeometry;
  40413. }(_PrimitiveGeometry));
  40414. BABYLON.BoxGeometry = BoxGeometry;
  40415. /**
  40416. * Creates a sphere geometry
  40417. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40418. */
  40419. var SphereGeometry = /** @class */ (function (_super) {
  40420. __extends(SphereGeometry, _super);
  40421. /**
  40422. * Create a new sphere geometry
  40423. * @param id defines the unique ID of the geometry
  40424. * @param scene defines the hosting scene
  40425. * @param segments defines the number of segments to use to create the sphere
  40426. * @param diameter defines the diameter of the sphere
  40427. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40428. * @param mesh defines the hosting mesh (can be null)
  40429. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40430. */
  40431. function SphereGeometry(id, scene,
  40432. /**
  40433. * Defines the number of segments to use to create the sphere
  40434. */
  40435. segments,
  40436. /**
  40437. * Defines the diameter of the sphere
  40438. */
  40439. diameter, canBeRegenerated, mesh,
  40440. /**
  40441. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40442. */
  40443. side) {
  40444. if (mesh === void 0) { mesh = null; }
  40445. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40446. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40447. _this.segments = segments;
  40448. _this.diameter = diameter;
  40449. _this.side = side;
  40450. return _this;
  40451. }
  40452. SphereGeometry.prototype._regenerateVertexData = function () {
  40453. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40454. };
  40455. SphereGeometry.prototype.copy = function (id) {
  40456. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40457. };
  40458. SphereGeometry.prototype.serialize = function () {
  40459. var serializationObject = _super.prototype.serialize.call(this);
  40460. serializationObject.segments = this.segments;
  40461. serializationObject.diameter = this.diameter;
  40462. return serializationObject;
  40463. };
  40464. SphereGeometry.Parse = function (parsedSphere, scene) {
  40465. if (scene.getGeometryByID(parsedSphere.id)) {
  40466. return null; // null since geometry could be something else than a sphere...
  40467. }
  40468. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40469. if (BABYLON.Tags) {
  40470. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40471. }
  40472. scene.pushGeometry(sphere, true);
  40473. return sphere;
  40474. };
  40475. return SphereGeometry;
  40476. }(_PrimitiveGeometry));
  40477. BABYLON.SphereGeometry = SphereGeometry;
  40478. /**
  40479. * Creates a disc geometry
  40480. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40481. */
  40482. var DiscGeometry = /** @class */ (function (_super) {
  40483. __extends(DiscGeometry, _super);
  40484. /**
  40485. * Creates a new disc geometry
  40486. * @param id defines the unique ID of the geometry
  40487. * @param scene defines the hosting scene
  40488. * @param radius defines the radius of the disc
  40489. * @param tessellation defines the tesselation factor to apply to the disc
  40490. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40491. * @param mesh defines the hosting mesh (can be null)
  40492. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40493. */
  40494. function DiscGeometry(id, scene,
  40495. /**
  40496. * Defines the radius of the disc
  40497. */
  40498. radius,
  40499. /**
  40500. * Defines the tesselation factor to apply to the disc
  40501. */
  40502. tessellation, canBeRegenerated, mesh,
  40503. /**
  40504. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40505. */
  40506. side) {
  40507. if (mesh === void 0) { mesh = null; }
  40508. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40509. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40510. _this.radius = radius;
  40511. _this.tessellation = tessellation;
  40512. _this.side = side;
  40513. return _this;
  40514. }
  40515. DiscGeometry.prototype._regenerateVertexData = function () {
  40516. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40517. };
  40518. DiscGeometry.prototype.copy = function (id) {
  40519. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40520. };
  40521. return DiscGeometry;
  40522. }(_PrimitiveGeometry));
  40523. BABYLON.DiscGeometry = DiscGeometry;
  40524. /**
  40525. * Creates a new cylinder geometry
  40526. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40527. */
  40528. var CylinderGeometry = /** @class */ (function (_super) {
  40529. __extends(CylinderGeometry, _super);
  40530. /**
  40531. * Creates a new cylinder geometry
  40532. * @param id defines the unique ID of the geometry
  40533. * @param scene defines the hosting scene
  40534. * @param height defines the height of the cylinder
  40535. * @param diameterTop defines the diameter of the cylinder's top cap
  40536. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40537. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40538. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40539. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40540. * @param mesh defines the hosting mesh (can be null)
  40541. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40542. */
  40543. function CylinderGeometry(id, scene,
  40544. /**
  40545. * Defines the height of the cylinder
  40546. */
  40547. height,
  40548. /**
  40549. * Defines the diameter of the cylinder's top cap
  40550. */
  40551. diameterTop,
  40552. /**
  40553. * Defines the diameter of the cylinder's bottom cap
  40554. */
  40555. diameterBottom,
  40556. /**
  40557. * Defines the tessellation factor to apply to the cylinder
  40558. */
  40559. tessellation,
  40560. /**
  40561. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40562. */
  40563. subdivisions, canBeRegenerated, mesh,
  40564. /**
  40565. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40566. */
  40567. side) {
  40568. if (subdivisions === void 0) { subdivisions = 1; }
  40569. if (mesh === void 0) { mesh = null; }
  40570. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40571. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40572. _this.height = height;
  40573. _this.diameterTop = diameterTop;
  40574. _this.diameterBottom = diameterBottom;
  40575. _this.tessellation = tessellation;
  40576. _this.subdivisions = subdivisions;
  40577. _this.side = side;
  40578. return _this;
  40579. }
  40580. CylinderGeometry.prototype._regenerateVertexData = function () {
  40581. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40582. };
  40583. CylinderGeometry.prototype.copy = function (id) {
  40584. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40585. };
  40586. CylinderGeometry.prototype.serialize = function () {
  40587. var serializationObject = _super.prototype.serialize.call(this);
  40588. serializationObject.height = this.height;
  40589. serializationObject.diameterTop = this.diameterTop;
  40590. serializationObject.diameterBottom = this.diameterBottom;
  40591. serializationObject.tessellation = this.tessellation;
  40592. return serializationObject;
  40593. };
  40594. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40595. if (scene.getGeometryByID(parsedCylinder.id)) {
  40596. return null; // null since geometry could be something else than a cylinder...
  40597. }
  40598. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40599. if (BABYLON.Tags) {
  40600. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40601. }
  40602. scene.pushGeometry(cylinder, true);
  40603. return cylinder;
  40604. };
  40605. return CylinderGeometry;
  40606. }(_PrimitiveGeometry));
  40607. BABYLON.CylinderGeometry = CylinderGeometry;
  40608. /**
  40609. * Creates a new torus geometry
  40610. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40611. */
  40612. var TorusGeometry = /** @class */ (function (_super) {
  40613. __extends(TorusGeometry, _super);
  40614. /**
  40615. * Creates a new torus geometry
  40616. * @param id defines the unique ID of the geometry
  40617. * @param scene defines the hosting scene
  40618. * @param diameter defines the diameter of the torus
  40619. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40620. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40621. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40622. * @param mesh defines the hosting mesh (can be null)
  40623. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40624. */
  40625. function TorusGeometry(id, scene,
  40626. /**
  40627. * Defines the diameter of the torus
  40628. */
  40629. diameter,
  40630. /**
  40631. * Defines the thickness of the torus (ie. internal diameter)
  40632. */
  40633. thickness,
  40634. /**
  40635. * Defines the tesselation factor to apply to the torus
  40636. */
  40637. tessellation, canBeRegenerated, mesh,
  40638. /**
  40639. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40640. */
  40641. side) {
  40642. if (mesh === void 0) { mesh = null; }
  40643. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40644. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40645. _this.diameter = diameter;
  40646. _this.thickness = thickness;
  40647. _this.tessellation = tessellation;
  40648. _this.side = side;
  40649. return _this;
  40650. }
  40651. TorusGeometry.prototype._regenerateVertexData = function () {
  40652. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40653. };
  40654. TorusGeometry.prototype.copy = function (id) {
  40655. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40656. };
  40657. TorusGeometry.prototype.serialize = function () {
  40658. var serializationObject = _super.prototype.serialize.call(this);
  40659. serializationObject.diameter = this.diameter;
  40660. serializationObject.thickness = this.thickness;
  40661. serializationObject.tessellation = this.tessellation;
  40662. return serializationObject;
  40663. };
  40664. TorusGeometry.Parse = function (parsedTorus, scene) {
  40665. if (scene.getGeometryByID(parsedTorus.id)) {
  40666. return null; // null since geometry could be something else than a torus...
  40667. }
  40668. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40669. if (BABYLON.Tags) {
  40670. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40671. }
  40672. scene.pushGeometry(torus, true);
  40673. return torus;
  40674. };
  40675. return TorusGeometry;
  40676. }(_PrimitiveGeometry));
  40677. BABYLON.TorusGeometry = TorusGeometry;
  40678. /**
  40679. * Creates a new ground geometry
  40680. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40681. */
  40682. var GroundGeometry = /** @class */ (function (_super) {
  40683. __extends(GroundGeometry, _super);
  40684. /**
  40685. * Creates a new ground geometry
  40686. * @param id defines the unique ID of the geometry
  40687. * @param scene defines the hosting scene
  40688. * @param width defines the width of the ground
  40689. * @param height defines the height of the ground
  40690. * @param subdivisions defines the subdivisions to apply to the ground
  40691. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40692. * @param mesh defines the hosting mesh (can be null)
  40693. */
  40694. function GroundGeometry(id, scene,
  40695. /**
  40696. * Defines the width of the ground
  40697. */
  40698. width,
  40699. /**
  40700. * Defines the height of the ground
  40701. */
  40702. height,
  40703. /**
  40704. * Defines the subdivisions to apply to the ground
  40705. */
  40706. subdivisions, canBeRegenerated, mesh) {
  40707. if (mesh === void 0) { mesh = null; }
  40708. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40709. _this.width = width;
  40710. _this.height = height;
  40711. _this.subdivisions = subdivisions;
  40712. return _this;
  40713. }
  40714. GroundGeometry.prototype._regenerateVertexData = function () {
  40715. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40716. };
  40717. GroundGeometry.prototype.copy = function (id) {
  40718. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40719. };
  40720. GroundGeometry.prototype.serialize = function () {
  40721. var serializationObject = _super.prototype.serialize.call(this);
  40722. serializationObject.width = this.width;
  40723. serializationObject.height = this.height;
  40724. serializationObject.subdivisions = this.subdivisions;
  40725. return serializationObject;
  40726. };
  40727. GroundGeometry.Parse = function (parsedGround, scene) {
  40728. if (scene.getGeometryByID(parsedGround.id)) {
  40729. return null; // null since geometry could be something else than a ground...
  40730. }
  40731. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40732. if (BABYLON.Tags) {
  40733. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40734. }
  40735. scene.pushGeometry(ground, true);
  40736. return ground;
  40737. };
  40738. return GroundGeometry;
  40739. }(_PrimitiveGeometry));
  40740. BABYLON.GroundGeometry = GroundGeometry;
  40741. /**
  40742. * Creates a tiled ground geometry
  40743. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40744. */
  40745. var TiledGroundGeometry = /** @class */ (function (_super) {
  40746. __extends(TiledGroundGeometry, _super);
  40747. /**
  40748. * Creates a tiled ground geometry
  40749. * @param id defines the unique ID of the geometry
  40750. * @param scene defines the hosting scene
  40751. * @param xmin defines the minimum value on X axis
  40752. * @param zmin defines the minimum value on Z axis
  40753. * @param xmax defines the maximum value on X axis
  40754. * @param zmax defines the maximum value on Z axis
  40755. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40756. * @param precision defines the precision to use when computing the tiles
  40757. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40758. * @param mesh defines the hosting mesh (can be null)
  40759. */
  40760. function TiledGroundGeometry(id, scene,
  40761. /**
  40762. * Defines the minimum value on X axis
  40763. */
  40764. xmin,
  40765. /**
  40766. * Defines the minimum value on Z axis
  40767. */
  40768. zmin,
  40769. /**
  40770. * Defines the maximum value on X axis
  40771. */
  40772. xmax,
  40773. /**
  40774. * Defines the maximum value on Z axis
  40775. */
  40776. zmax,
  40777. /**
  40778. * Defines the subdivisions to apply to the ground
  40779. */
  40780. subdivisions,
  40781. /**
  40782. * Defines the precision to use when computing the tiles
  40783. */
  40784. precision, canBeRegenerated, mesh) {
  40785. if (mesh === void 0) { mesh = null; }
  40786. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40787. _this.xmin = xmin;
  40788. _this.zmin = zmin;
  40789. _this.xmax = xmax;
  40790. _this.zmax = zmax;
  40791. _this.subdivisions = subdivisions;
  40792. _this.precision = precision;
  40793. return _this;
  40794. }
  40795. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40796. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40797. };
  40798. TiledGroundGeometry.prototype.copy = function (id) {
  40799. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40800. };
  40801. return TiledGroundGeometry;
  40802. }(_PrimitiveGeometry));
  40803. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40804. /**
  40805. * Creates a plane geometry
  40806. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40807. */
  40808. var PlaneGeometry = /** @class */ (function (_super) {
  40809. __extends(PlaneGeometry, _super);
  40810. /**
  40811. * Creates a plane geometry
  40812. * @param id defines the unique ID of the geometry
  40813. * @param scene defines the hosting scene
  40814. * @param size defines the size of the plane (width === height)
  40815. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40816. * @param mesh defines the hosting mesh (can be null)
  40817. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40818. */
  40819. function PlaneGeometry(id, scene,
  40820. /**
  40821. * Defines the size of the plane (width === height)
  40822. */
  40823. size, canBeRegenerated, mesh,
  40824. /**
  40825. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40826. */
  40827. side) {
  40828. if (mesh === void 0) { mesh = null; }
  40829. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40830. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40831. _this.size = size;
  40832. _this.side = side;
  40833. return _this;
  40834. }
  40835. PlaneGeometry.prototype._regenerateVertexData = function () {
  40836. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40837. };
  40838. PlaneGeometry.prototype.copy = function (id) {
  40839. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40840. };
  40841. PlaneGeometry.prototype.serialize = function () {
  40842. var serializationObject = _super.prototype.serialize.call(this);
  40843. serializationObject.size = this.size;
  40844. return serializationObject;
  40845. };
  40846. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40847. if (scene.getGeometryByID(parsedPlane.id)) {
  40848. return null; // null since geometry could be something else than a ground...
  40849. }
  40850. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40851. if (BABYLON.Tags) {
  40852. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40853. }
  40854. scene.pushGeometry(plane, true);
  40855. return plane;
  40856. };
  40857. return PlaneGeometry;
  40858. }(_PrimitiveGeometry));
  40859. BABYLON.PlaneGeometry = PlaneGeometry;
  40860. /**
  40861. * Creates a torus knot geometry
  40862. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40863. */
  40864. var TorusKnotGeometry = /** @class */ (function (_super) {
  40865. __extends(TorusKnotGeometry, _super);
  40866. /**
  40867. * Creates a torus knot geometry
  40868. * @param id defines the unique ID of the geometry
  40869. * @param scene defines the hosting scene
  40870. * @param radius defines the radius of the torus knot
  40871. * @param tube defines the thickness of the torus knot tube
  40872. * @param radialSegments defines the number of radial segments
  40873. * @param tubularSegments defines the number of tubular segments
  40874. * @param p defines the first number of windings
  40875. * @param q defines the second number of windings
  40876. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40877. * @param mesh defines the hosting mesh (can be null)
  40878. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40879. */
  40880. function TorusKnotGeometry(id, scene,
  40881. /**
  40882. * Defines the radius of the torus knot
  40883. */
  40884. radius,
  40885. /**
  40886. * Defines the thickness of the torus knot tube
  40887. */
  40888. tube,
  40889. /**
  40890. * Defines the number of radial segments
  40891. */
  40892. radialSegments,
  40893. /**
  40894. * Defines the number of tubular segments
  40895. */
  40896. tubularSegments,
  40897. /**
  40898. * Defines the first number of windings
  40899. */
  40900. p,
  40901. /**
  40902. * Defines the second number of windings
  40903. */
  40904. q, canBeRegenerated, mesh,
  40905. /**
  40906. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40907. */
  40908. side) {
  40909. if (mesh === void 0) { mesh = null; }
  40910. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40911. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40912. _this.radius = radius;
  40913. _this.tube = tube;
  40914. _this.radialSegments = radialSegments;
  40915. _this.tubularSegments = tubularSegments;
  40916. _this.p = p;
  40917. _this.q = q;
  40918. _this.side = side;
  40919. return _this;
  40920. }
  40921. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40922. 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 });
  40923. };
  40924. TorusKnotGeometry.prototype.copy = function (id) {
  40925. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40926. };
  40927. TorusKnotGeometry.prototype.serialize = function () {
  40928. var serializationObject = _super.prototype.serialize.call(this);
  40929. serializationObject.radius = this.radius;
  40930. serializationObject.tube = this.tube;
  40931. serializationObject.radialSegments = this.radialSegments;
  40932. serializationObject.tubularSegments = this.tubularSegments;
  40933. serializationObject.p = this.p;
  40934. serializationObject.q = this.q;
  40935. return serializationObject;
  40936. };
  40937. ;
  40938. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40939. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40940. return null; // null since geometry could be something else than a ground...
  40941. }
  40942. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40943. if (BABYLON.Tags) {
  40944. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40945. }
  40946. scene.pushGeometry(torusKnot, true);
  40947. return torusKnot;
  40948. };
  40949. return TorusKnotGeometry;
  40950. }(_PrimitiveGeometry));
  40951. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40952. //}
  40953. })(BABYLON || (BABYLON = {}));
  40954. //# sourceMappingURL=babylon.geometry.js.map
  40955. var BABYLON;
  40956. (function (BABYLON) {
  40957. /**
  40958. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40959. */
  40960. var PerformanceMonitor = /** @class */ (function () {
  40961. /**
  40962. * constructor
  40963. * @param frameSampleSize The number of samples required to saturate the sliding window
  40964. */
  40965. function PerformanceMonitor(frameSampleSize) {
  40966. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40967. this._enabled = true;
  40968. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40969. }
  40970. /**
  40971. * Samples current frame
  40972. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40973. */
  40974. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40975. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40976. if (!this._enabled)
  40977. return;
  40978. if (this._lastFrameTimeMs != null) {
  40979. var dt = timeMs - this._lastFrameTimeMs;
  40980. this._rollingFrameTime.add(dt);
  40981. }
  40982. this._lastFrameTimeMs = timeMs;
  40983. };
  40984. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40985. /**
  40986. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40987. * @return Average frame time in milliseconds
  40988. */
  40989. get: function () {
  40990. return this._rollingFrameTime.average;
  40991. },
  40992. enumerable: true,
  40993. configurable: true
  40994. });
  40995. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40996. /**
  40997. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40998. * @return Frame time variance in milliseconds squared
  40999. */
  41000. get: function () {
  41001. return this._rollingFrameTime.variance;
  41002. },
  41003. enumerable: true,
  41004. configurable: true
  41005. });
  41006. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41007. /**
  41008. * Returns the frame time of the most recent frame
  41009. * @return Frame time in milliseconds
  41010. */
  41011. get: function () {
  41012. return this._rollingFrameTime.history(0);
  41013. },
  41014. enumerable: true,
  41015. configurable: true
  41016. });
  41017. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41018. /**
  41019. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41020. * @return Framerate in frames per second
  41021. */
  41022. get: function () {
  41023. return 1000.0 / this._rollingFrameTime.average;
  41024. },
  41025. enumerable: true,
  41026. configurable: true
  41027. });
  41028. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41029. /**
  41030. * Returns the average framerate in frames per second using the most recent frame time
  41031. * @return Framerate in frames per second
  41032. */
  41033. get: function () {
  41034. var history = this._rollingFrameTime.history(0);
  41035. if (history === 0) {
  41036. return 0;
  41037. }
  41038. return 1000.0 / history;
  41039. },
  41040. enumerable: true,
  41041. configurable: true
  41042. });
  41043. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41044. /**
  41045. * Returns true if enough samples have been taken to completely fill the sliding window
  41046. * @return true if saturated
  41047. */
  41048. get: function () {
  41049. return this._rollingFrameTime.isSaturated();
  41050. },
  41051. enumerable: true,
  41052. configurable: true
  41053. });
  41054. /**
  41055. * Enables contributions to the sliding window sample set
  41056. */
  41057. PerformanceMonitor.prototype.enable = function () {
  41058. this._enabled = true;
  41059. };
  41060. /**
  41061. * Disables contributions to the sliding window sample set
  41062. * Samples will not be interpolated over the disabled period
  41063. */
  41064. PerformanceMonitor.prototype.disable = function () {
  41065. this._enabled = false;
  41066. //clear last sample to avoid interpolating over the disabled period when next enabled
  41067. this._lastFrameTimeMs = null;
  41068. };
  41069. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41070. /**
  41071. * Returns true if sampling is enabled
  41072. * @return true if enabled
  41073. */
  41074. get: function () {
  41075. return this._enabled;
  41076. },
  41077. enumerable: true,
  41078. configurable: true
  41079. });
  41080. /**
  41081. * Resets performance monitor
  41082. */
  41083. PerformanceMonitor.prototype.reset = function () {
  41084. //clear last sample to avoid interpolating over the disabled period when next enabled
  41085. this._lastFrameTimeMs = null;
  41086. //wipe record
  41087. this._rollingFrameTime.reset();
  41088. };
  41089. return PerformanceMonitor;
  41090. }());
  41091. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41092. /**
  41093. * RollingAverage
  41094. *
  41095. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41096. */
  41097. var RollingAverage = /** @class */ (function () {
  41098. /**
  41099. * constructor
  41100. * @param length The number of samples required to saturate the sliding window
  41101. */
  41102. function RollingAverage(length) {
  41103. this._samples = new Array(length);
  41104. this.reset();
  41105. }
  41106. /**
  41107. * Adds a sample to the sample set
  41108. * @param v The sample value
  41109. */
  41110. RollingAverage.prototype.add = function (v) {
  41111. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41112. var delta;
  41113. //we need to check if we've already wrapped round
  41114. if (this.isSaturated()) {
  41115. //remove bottom of stack from mean
  41116. var bottomValue = this._samples[this._pos];
  41117. delta = bottomValue - this.average;
  41118. this.average -= delta / (this._sampleCount - 1);
  41119. this._m2 -= delta * (bottomValue - this.average);
  41120. }
  41121. else {
  41122. this._sampleCount++;
  41123. }
  41124. //add new value to mean
  41125. delta = v - this.average;
  41126. this.average += delta / (this._sampleCount);
  41127. this._m2 += delta * (v - this.average);
  41128. //set the new variance
  41129. this.variance = this._m2 / (this._sampleCount - 1);
  41130. this._samples[this._pos] = v;
  41131. this._pos++;
  41132. this._pos %= this._samples.length; //positive wrap around
  41133. };
  41134. /**
  41135. * Returns previously added values or null if outside of history or outside the sliding window domain
  41136. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41137. * @return Value previously recorded with add() or null if outside of range
  41138. */
  41139. RollingAverage.prototype.history = function (i) {
  41140. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41141. return 0;
  41142. }
  41143. var i0 = this._wrapPosition(this._pos - 1.0);
  41144. return this._samples[this._wrapPosition(i0 - i)];
  41145. };
  41146. /**
  41147. * Returns true if enough samples have been taken to completely fill the sliding window
  41148. * @return true if sample-set saturated
  41149. */
  41150. RollingAverage.prototype.isSaturated = function () {
  41151. return this._sampleCount >= this._samples.length;
  41152. };
  41153. /**
  41154. * Resets the rolling average (equivalent to 0 samples taken so far)
  41155. */
  41156. RollingAverage.prototype.reset = function () {
  41157. this.average = 0;
  41158. this.variance = 0;
  41159. this._sampleCount = 0;
  41160. this._pos = 0;
  41161. this._m2 = 0;
  41162. };
  41163. /**
  41164. * Wraps a value around the sample range boundaries
  41165. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41166. * @return Wrapped position in sample range
  41167. */
  41168. RollingAverage.prototype._wrapPosition = function (i) {
  41169. var max = this._samples.length;
  41170. return ((i % max) + max) % max;
  41171. };
  41172. return RollingAverage;
  41173. }());
  41174. BABYLON.RollingAverage = RollingAverage;
  41175. })(BABYLON || (BABYLON = {}));
  41176. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41177. var BABYLON;
  41178. (function (BABYLON) {
  41179. /**
  41180. * "Static Class" containing the most commonly used helper while dealing with material for
  41181. * rendering purpose.
  41182. *
  41183. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41184. *
  41185. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41186. */
  41187. var MaterialHelper = /** @class */ (function () {
  41188. function MaterialHelper() {
  41189. }
  41190. /**
  41191. * Bind the current view position to an effect.
  41192. * @param effect The effect to be bound
  41193. * @param scene The scene the eyes position is used from
  41194. */
  41195. MaterialHelper.BindEyePosition = function (effect, scene) {
  41196. if (scene._forcedViewPosition) {
  41197. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41198. return;
  41199. }
  41200. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41201. };
  41202. /**
  41203. * Helps preparing the defines values about the UVs in used in the effect.
  41204. * UVs are shared as much as we can accross chanels in the shaders.
  41205. * @param texture The texture we are preparing the UVs for
  41206. * @param defines The defines to update
  41207. * @param key The chanel key "diffuse", "specular"... used in the shader
  41208. */
  41209. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41210. defines._needUVs = true;
  41211. defines[key] = true;
  41212. if (texture.getTextureMatrix().isIdentity(true)) {
  41213. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41214. if (texture.coordinatesIndex === 0) {
  41215. defines["MAINUV1"] = true;
  41216. }
  41217. else {
  41218. defines["MAINUV2"] = true;
  41219. }
  41220. }
  41221. else {
  41222. defines[key + "DIRECTUV"] = 0;
  41223. }
  41224. };
  41225. /**
  41226. * Binds a texture matrix value to its corrsponding uniform
  41227. * @param texture The texture to bind the matrix for
  41228. * @param uniformBuffer The uniform buffer receivin the data
  41229. * @param key The chanel key "diffuse", "specular"... used in the shader
  41230. */
  41231. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41232. var matrix = texture.getTextureMatrix();
  41233. if (!matrix.isIdentity(true)) {
  41234. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41235. }
  41236. };
  41237. /**
  41238. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41239. * @param mesh defines the current mesh
  41240. * @param scene defines the current scene
  41241. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41242. * @param pointsCloud defines if point cloud rendering has to be turned on
  41243. * @param fogEnabled defines if fog has to be turned on
  41244. * @param alphaTest defines if alpha testing has to be turned on
  41245. * @param defines defines the current list of defines
  41246. */
  41247. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41248. if (defines._areMiscDirty) {
  41249. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41250. defines["POINTSIZE"] = pointsCloud;
  41251. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41252. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41253. defines["ALPHATEST"] = alphaTest;
  41254. }
  41255. };
  41256. /**
  41257. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41258. * @param scene defines the current scene
  41259. * @param engine defines the current engine
  41260. * @param defines specifies the list of active defines
  41261. * @param useInstances defines if instances have to be turned on
  41262. * @param useClipPlane defines if clip plane have to be turned on
  41263. */
  41264. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41265. if (useClipPlane === void 0) { useClipPlane = null; }
  41266. var changed = false;
  41267. if (useClipPlane == null) {
  41268. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41269. }
  41270. if (defines["CLIPPLANE"] !== useClipPlane) {
  41271. defines["CLIPPLANE"] = useClipPlane;
  41272. changed = true;
  41273. }
  41274. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41275. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41276. changed = true;
  41277. }
  41278. if (defines["INSTANCES"] !== useInstances) {
  41279. defines["INSTANCES"] = useInstances;
  41280. changed = true;
  41281. }
  41282. if (changed) {
  41283. defines.markAsUnprocessed();
  41284. }
  41285. };
  41286. /**
  41287. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41288. * @param mesh The mesh containing the geometry data we will draw
  41289. * @param defines The defines to update
  41290. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41291. * @param useBones Precise whether bones should be used or not (override mesh info)
  41292. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41293. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41294. * @returns false if defines are considered not dirty and have not been checked
  41295. */
  41296. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41297. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41298. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41299. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41300. return false;
  41301. }
  41302. defines._normals = defines._needNormals;
  41303. defines._uvs = defines._needUVs;
  41304. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41305. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41306. defines["TANGENT"] = true;
  41307. }
  41308. if (defines._needUVs) {
  41309. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41310. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41311. }
  41312. else {
  41313. defines["UV1"] = false;
  41314. defines["UV2"] = false;
  41315. }
  41316. if (useVertexColor) {
  41317. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41318. defines["VERTEXCOLOR"] = hasVertexColors;
  41319. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41320. }
  41321. if (useBones) {
  41322. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41323. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41324. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41325. }
  41326. else {
  41327. defines["NUM_BONE_INFLUENCERS"] = 0;
  41328. defines["BonesPerMesh"] = 0;
  41329. }
  41330. }
  41331. if (useMorphTargets) {
  41332. var manager = mesh.morphTargetManager;
  41333. if (manager) {
  41334. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41335. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41336. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41337. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41338. }
  41339. else {
  41340. defines["MORPHTARGETS_TANGENT"] = false;
  41341. defines["MORPHTARGETS_NORMAL"] = false;
  41342. defines["MORPHTARGETS"] = false;
  41343. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41344. }
  41345. }
  41346. return true;
  41347. };
  41348. /**
  41349. * Prepares the defines related to the light information passed in parameter
  41350. * @param scene The scene we are intending to draw
  41351. * @param mesh The mesh the effect is compiling for
  41352. * @param defines The defines to update
  41353. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41354. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41355. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41356. * @returns true if normals will be required for the rest of the effect
  41357. */
  41358. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41359. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41360. if (disableLighting === void 0) { disableLighting = false; }
  41361. if (!defines._areLightsDirty) {
  41362. return defines._needNormals;
  41363. }
  41364. var lightIndex = 0;
  41365. var needNormals = false;
  41366. var needRebuild = false;
  41367. var lightmapMode = false;
  41368. var shadowEnabled = false;
  41369. var specularEnabled = false;
  41370. if (scene.lightsEnabled && !disableLighting) {
  41371. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41372. var light = _a[_i];
  41373. needNormals = true;
  41374. if (defines["LIGHT" + lightIndex] === undefined) {
  41375. needRebuild = true;
  41376. }
  41377. defines["LIGHT" + lightIndex] = true;
  41378. defines["SPOTLIGHT" + lightIndex] = false;
  41379. defines["HEMILIGHT" + lightIndex] = false;
  41380. defines["POINTLIGHT" + lightIndex] = false;
  41381. defines["DIRLIGHT" + lightIndex] = false;
  41382. var type;
  41383. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41384. type = "SPOTLIGHT" + lightIndex;
  41385. var spotLight = light;
  41386. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41387. }
  41388. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41389. type = "HEMILIGHT" + lightIndex;
  41390. }
  41391. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41392. type = "POINTLIGHT" + lightIndex;
  41393. }
  41394. else {
  41395. type = "DIRLIGHT" + lightIndex;
  41396. }
  41397. defines[type] = true;
  41398. // Specular
  41399. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41400. specularEnabled = true;
  41401. }
  41402. // Shadows
  41403. defines["SHADOW" + lightIndex] = false;
  41404. defines["SHADOWPCF" + lightIndex] = false;
  41405. defines["SHADOWPCSS" + lightIndex] = false;
  41406. defines["SHADOWPOISSON" + lightIndex] = false;
  41407. defines["SHADOWESM" + lightIndex] = false;
  41408. defines["SHADOWCUBE" + lightIndex] = false;
  41409. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41410. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41411. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41412. var shadowGenerator = light.getShadowGenerator();
  41413. if (shadowGenerator) {
  41414. shadowEnabled = true;
  41415. shadowGenerator.prepareDefines(defines, lightIndex);
  41416. }
  41417. }
  41418. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41419. lightmapMode = true;
  41420. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41421. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41422. }
  41423. else {
  41424. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41425. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41426. }
  41427. lightIndex++;
  41428. if (lightIndex === maxSimultaneousLights)
  41429. break;
  41430. }
  41431. }
  41432. defines["SPECULARTERM"] = specularEnabled;
  41433. defines["SHADOWS"] = shadowEnabled;
  41434. // Resetting all other lights if any
  41435. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41436. if (defines["LIGHT" + index] !== undefined) {
  41437. defines["LIGHT" + index] = false;
  41438. defines["HEMILIGHT" + lightIndex] = false;
  41439. defines["POINTLIGHT" + lightIndex] = false;
  41440. defines["DIRLIGHT" + lightIndex] = false;
  41441. defines["SPOTLIGHT" + lightIndex] = false;
  41442. defines["SHADOW" + lightIndex] = false;
  41443. }
  41444. }
  41445. var caps = scene.getEngine().getCaps();
  41446. if (defines["SHADOWFLOAT"] === undefined) {
  41447. needRebuild = true;
  41448. }
  41449. defines["SHADOWFLOAT"] = shadowEnabled &&
  41450. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41451. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41452. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41453. if (needRebuild) {
  41454. defines.rebuild();
  41455. }
  41456. return needNormals;
  41457. };
  41458. /**
  41459. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41460. * that won t be acctive due to defines being turned off.
  41461. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41462. * @param samplersList The samplers list
  41463. * @param defines The defines helping in the list generation
  41464. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41465. */
  41466. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41467. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41468. var uniformsList;
  41469. var uniformBuffersList = null;
  41470. if (uniformsListOrOptions.uniformsNames) {
  41471. var options = uniformsListOrOptions;
  41472. uniformsList = options.uniformsNames;
  41473. uniformBuffersList = options.uniformBuffersNames;
  41474. samplersList = options.samplers;
  41475. defines = options.defines;
  41476. maxSimultaneousLights = options.maxSimultaneousLights;
  41477. }
  41478. else {
  41479. uniformsList = uniformsListOrOptions;
  41480. if (!samplersList) {
  41481. samplersList = [];
  41482. }
  41483. }
  41484. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41485. if (!defines["LIGHT" + lightIndex]) {
  41486. break;
  41487. }
  41488. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41489. if (uniformBuffersList) {
  41490. uniformBuffersList.push("Light" + lightIndex);
  41491. }
  41492. samplersList.push("shadowSampler" + lightIndex);
  41493. samplersList.push("depthSampler" + lightIndex);
  41494. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41495. samplersList.push("projectionLightSampler" + lightIndex);
  41496. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41497. }
  41498. }
  41499. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41500. uniformsList.push("morphTargetInfluences");
  41501. }
  41502. };
  41503. /**
  41504. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41505. * @param defines The defines to update while falling back
  41506. * @param fallbacks The authorized effect fallbacks
  41507. * @param maxSimultaneousLights The maximum number of lights allowed
  41508. * @param rank the current rank of the Effect
  41509. * @returns The newly affected rank
  41510. */
  41511. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41512. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41513. if (rank === void 0) { rank = 0; }
  41514. var lightFallbackRank = 0;
  41515. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41516. if (!defines["LIGHT" + lightIndex]) {
  41517. break;
  41518. }
  41519. if (lightIndex > 0) {
  41520. lightFallbackRank = rank + lightIndex;
  41521. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41522. }
  41523. if (!defines["SHADOWS"]) {
  41524. if (defines["SHADOW" + lightIndex]) {
  41525. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41526. }
  41527. if (defines["SHADOWPCF" + lightIndex]) {
  41528. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41529. }
  41530. if (defines["SHADOWPCSS" + lightIndex]) {
  41531. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41532. }
  41533. if (defines["SHADOWPOISSON" + lightIndex]) {
  41534. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41535. }
  41536. if (defines["SHADOWESM" + lightIndex]) {
  41537. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41538. }
  41539. }
  41540. }
  41541. return lightFallbackRank++;
  41542. };
  41543. /**
  41544. * Prepares the list of attributes required for morph targets according to the effect defines.
  41545. * @param attribs The current list of supported attribs
  41546. * @param mesh The mesh to prepare the morph targets attributes for
  41547. * @param defines The current Defines of the effect
  41548. */
  41549. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41550. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41551. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41552. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41553. var manager = mesh.morphTargetManager;
  41554. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41555. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41556. for (var index = 0; index < influencers; index++) {
  41557. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41558. if (normal) {
  41559. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41560. }
  41561. if (tangent) {
  41562. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41563. }
  41564. if (attribs.length > maxAttributesCount) {
  41565. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41566. }
  41567. }
  41568. }
  41569. };
  41570. /**
  41571. * Prepares the list of attributes required for bones according to the effect defines.
  41572. * @param attribs The current list of supported attribs
  41573. * @param mesh The mesh to prepare the bones attributes for
  41574. * @param defines The current Defines of the effect
  41575. * @param fallbacks The current efffect fallback strategy
  41576. */
  41577. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41578. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41579. fallbacks.addCPUSkinningFallback(0, mesh);
  41580. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41581. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41582. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41583. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41584. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41585. }
  41586. }
  41587. };
  41588. /**
  41589. * Prepares the list of attributes required for instances according to the effect defines.
  41590. * @param attribs The current list of supported attribs
  41591. * @param defines The current Defines of the effect
  41592. */
  41593. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41594. if (defines["INSTANCES"]) {
  41595. attribs.push("world0");
  41596. attribs.push("world1");
  41597. attribs.push("world2");
  41598. attribs.push("world3");
  41599. }
  41600. };
  41601. /**
  41602. * Binds the light shadow information to the effect for the given mesh.
  41603. * @param light The light containing the generator
  41604. * @param scene The scene the lights belongs to
  41605. * @param mesh The mesh we are binding the information to render
  41606. * @param lightIndex The light index in the effect used to render the mesh
  41607. * @param effect The effect we are binding the data to
  41608. */
  41609. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41610. if (light.shadowEnabled && mesh.receiveShadows) {
  41611. var shadowGenerator = light.getShadowGenerator();
  41612. if (shadowGenerator) {
  41613. shadowGenerator.bindShadowLight(lightIndex, effect);
  41614. }
  41615. }
  41616. };
  41617. /**
  41618. * Binds the light information to the effect.
  41619. * @param light The light containing the generator
  41620. * @param effect The effect we are binding the data to
  41621. * @param lightIndex The light index in the effect used to render
  41622. */
  41623. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41624. light.transferToEffect(effect, lightIndex + "");
  41625. };
  41626. /**
  41627. * Binds the lights information from the scene to the effect for the given mesh.
  41628. * @param scene The scene the lights belongs to
  41629. * @param mesh The mesh we are binding the information to render
  41630. * @param effect The effect we are binding the data to
  41631. * @param defines The generated defines for the effect
  41632. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41633. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41634. */
  41635. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41636. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41637. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41638. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41639. for (var i = 0; i < len; i++) {
  41640. var light = mesh._lightSources[i];
  41641. var iAsString = i.toString();
  41642. var scaledIntensity = light.getScaledIntensity();
  41643. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41644. MaterialHelper.BindLightProperties(light, effect, i);
  41645. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41646. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41647. if (defines["SPECULARTERM"]) {
  41648. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41649. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41650. }
  41651. // Shadows
  41652. if (scene.shadowsEnabled) {
  41653. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41654. }
  41655. light._uniformBuffer.update();
  41656. }
  41657. };
  41658. /**
  41659. * Binds the fog information from the scene to the effect for the given mesh.
  41660. * @param scene The scene the lights belongs to
  41661. * @param mesh The mesh we are binding the information to render
  41662. * @param effect The effect we are binding the data to
  41663. */
  41664. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41665. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41666. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41667. effect.setColor3("vFogColor", scene.fogColor);
  41668. }
  41669. };
  41670. /**
  41671. * Binds the bones information from the mesh to the effect.
  41672. * @param mesh The mesh we are binding the information to render
  41673. * @param effect The effect we are binding the data to
  41674. */
  41675. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41676. if (!effect || !mesh) {
  41677. return;
  41678. }
  41679. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41680. mesh.computeBonesUsingShaders = false;
  41681. }
  41682. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41683. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41684. if (matrices) {
  41685. effect.setMatrices("mBones", matrices);
  41686. }
  41687. }
  41688. };
  41689. /**
  41690. * Binds the morph targets information from the mesh to the effect.
  41691. * @param abstractMesh The mesh we are binding the information to render
  41692. * @param effect The effect we are binding the data to
  41693. */
  41694. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41695. var manager = abstractMesh.morphTargetManager;
  41696. if (!abstractMesh || !manager) {
  41697. return;
  41698. }
  41699. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41700. };
  41701. /**
  41702. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41703. * @param defines The generated defines used in the effect
  41704. * @param effect The effect we are binding the data to
  41705. * @param scene The scene we are willing to render with logarithmic scale for
  41706. */
  41707. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41708. if (defines["LOGARITHMICDEPTH"]) {
  41709. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41710. }
  41711. };
  41712. /**
  41713. * Binds the clip plane information from the scene to the effect.
  41714. * @param scene The scene the clip plane information are extracted from
  41715. * @param effect The effect we are binding the data to
  41716. */
  41717. MaterialHelper.BindClipPlane = function (effect, scene) {
  41718. if (scene.clipPlane) {
  41719. var clipPlane = scene.clipPlane;
  41720. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41721. }
  41722. };
  41723. return MaterialHelper;
  41724. }());
  41725. BABYLON.MaterialHelper = MaterialHelper;
  41726. })(BABYLON || (BABYLON = {}));
  41727. //# sourceMappingURL=babylon.materialHelper.js.map
  41728. var BABYLON;
  41729. (function (BABYLON) {
  41730. var PushMaterial = /** @class */ (function (_super) {
  41731. __extends(PushMaterial, _super);
  41732. function PushMaterial(name, scene) {
  41733. var _this = _super.call(this, name, scene) || this;
  41734. _this._normalMatrix = new BABYLON.Matrix();
  41735. _this.storeEffectOnSubMeshes = true;
  41736. return _this;
  41737. }
  41738. PushMaterial.prototype.getEffect = function () {
  41739. return this._activeEffect;
  41740. };
  41741. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41742. if (!mesh) {
  41743. return false;
  41744. }
  41745. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41746. return true;
  41747. }
  41748. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41749. };
  41750. /**
  41751. * Binds the given world matrix to the active effect
  41752. *
  41753. * @param world the matrix to bind
  41754. */
  41755. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41756. this._activeEffect.setMatrix("world", world);
  41757. };
  41758. /**
  41759. * Binds the given normal matrix to the active effect
  41760. *
  41761. * @param normalMatrix the matrix to bind
  41762. */
  41763. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41764. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41765. };
  41766. PushMaterial.prototype.bind = function (world, mesh) {
  41767. if (!mesh) {
  41768. return;
  41769. }
  41770. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41771. };
  41772. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41773. if (effect === void 0) { effect = null; }
  41774. _super.prototype._afterBind.call(this, mesh);
  41775. this.getScene()._cachedEffect = effect;
  41776. };
  41777. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41778. if (visibility === void 0) { visibility = 1; }
  41779. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41780. };
  41781. return PushMaterial;
  41782. }(BABYLON.Material));
  41783. BABYLON.PushMaterial = PushMaterial;
  41784. })(BABYLON || (BABYLON = {}));
  41785. //# sourceMappingURL=babylon.pushMaterial.js.map
  41786. var BABYLON;
  41787. (function (BABYLON) {
  41788. /** @hidden */
  41789. var StandardMaterialDefines = /** @class */ (function (_super) {
  41790. __extends(StandardMaterialDefines, _super);
  41791. function StandardMaterialDefines() {
  41792. var _this = _super.call(this) || this;
  41793. _this.MAINUV1 = false;
  41794. _this.MAINUV2 = false;
  41795. _this.DIFFUSE = false;
  41796. _this.DIFFUSEDIRECTUV = 0;
  41797. _this.AMBIENT = false;
  41798. _this.AMBIENTDIRECTUV = 0;
  41799. _this.OPACITY = false;
  41800. _this.OPACITYDIRECTUV = 0;
  41801. _this.OPACITYRGB = false;
  41802. _this.REFLECTION = false;
  41803. _this.EMISSIVE = false;
  41804. _this.EMISSIVEDIRECTUV = 0;
  41805. _this.SPECULAR = false;
  41806. _this.SPECULARDIRECTUV = 0;
  41807. _this.BUMP = false;
  41808. _this.BUMPDIRECTUV = 0;
  41809. _this.PARALLAX = false;
  41810. _this.PARALLAXOCCLUSION = false;
  41811. _this.SPECULAROVERALPHA = false;
  41812. _this.CLIPPLANE = false;
  41813. _this.ALPHATEST = false;
  41814. _this.DEPTHPREPASS = false;
  41815. _this.ALPHAFROMDIFFUSE = false;
  41816. _this.POINTSIZE = false;
  41817. _this.FOG = false;
  41818. _this.SPECULARTERM = false;
  41819. _this.DIFFUSEFRESNEL = false;
  41820. _this.OPACITYFRESNEL = false;
  41821. _this.REFLECTIONFRESNEL = false;
  41822. _this.REFRACTIONFRESNEL = false;
  41823. _this.EMISSIVEFRESNEL = false;
  41824. _this.FRESNEL = false;
  41825. _this.NORMAL = false;
  41826. _this.UV1 = false;
  41827. _this.UV2 = false;
  41828. _this.VERTEXCOLOR = false;
  41829. _this.VERTEXALPHA = false;
  41830. _this.NUM_BONE_INFLUENCERS = 0;
  41831. _this.BonesPerMesh = 0;
  41832. _this.INSTANCES = false;
  41833. _this.GLOSSINESS = false;
  41834. _this.ROUGHNESS = false;
  41835. _this.EMISSIVEASILLUMINATION = false;
  41836. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41837. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41838. _this.LIGHTMAP = false;
  41839. _this.LIGHTMAPDIRECTUV = 0;
  41840. _this.OBJECTSPACE_NORMALMAP = false;
  41841. _this.USELIGHTMAPASSHADOWMAP = false;
  41842. _this.REFLECTIONMAP_3D = false;
  41843. _this.REFLECTIONMAP_SPHERICAL = false;
  41844. _this.REFLECTIONMAP_PLANAR = false;
  41845. _this.REFLECTIONMAP_CUBIC = false;
  41846. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41847. _this.REFLECTIONMAP_PROJECTION = false;
  41848. _this.REFLECTIONMAP_SKYBOX = false;
  41849. _this.REFLECTIONMAP_EXPLICIT = false;
  41850. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41851. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41852. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41853. _this.INVERTCUBICMAP = false;
  41854. _this.LOGARITHMICDEPTH = false;
  41855. _this.REFRACTION = false;
  41856. _this.REFRACTIONMAP_3D = false;
  41857. _this.REFLECTIONOVERALPHA = false;
  41858. _this.TWOSIDEDLIGHTING = false;
  41859. _this.SHADOWFLOAT = false;
  41860. _this.MORPHTARGETS = false;
  41861. _this.MORPHTARGETS_NORMAL = false;
  41862. _this.MORPHTARGETS_TANGENT = false;
  41863. _this.NUM_MORPH_INFLUENCERS = 0;
  41864. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41865. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41866. _this.IMAGEPROCESSING = false;
  41867. _this.VIGNETTE = false;
  41868. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41869. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41870. _this.TONEMAPPING = false;
  41871. _this.CONTRAST = false;
  41872. _this.COLORCURVES = false;
  41873. _this.COLORGRADING = false;
  41874. _this.COLORGRADING3D = false;
  41875. _this.SAMPLER3DGREENDEPTH = false;
  41876. _this.SAMPLER3DBGRMAP = false;
  41877. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41878. /**
  41879. * If the reflection texture on this material is in linear color space
  41880. * @hidden
  41881. */
  41882. _this.IS_REFLECTION_LINEAR = false;
  41883. /**
  41884. * If the refraction texture on this material is in linear color space
  41885. * @hidden
  41886. */
  41887. _this.IS_REFRACTION_LINEAR = false;
  41888. _this.EXPOSURE = false;
  41889. _this.rebuild();
  41890. return _this;
  41891. }
  41892. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41893. var modes = [
  41894. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41895. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41896. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41897. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41898. ];
  41899. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41900. var mode = modes_1[_i];
  41901. this[mode] = (mode === modeToEnable);
  41902. }
  41903. };
  41904. return StandardMaterialDefines;
  41905. }(BABYLON.MaterialDefines));
  41906. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41907. var StandardMaterial = /** @class */ (function (_super) {
  41908. __extends(StandardMaterial, _super);
  41909. function StandardMaterial(name, scene) {
  41910. var _this = _super.call(this, name, scene) || this;
  41911. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41912. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41913. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41914. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41915. _this.specularPower = 64;
  41916. _this._useAlphaFromDiffuseTexture = false;
  41917. _this._useEmissiveAsIllumination = false;
  41918. _this._linkEmissiveWithDiffuse = false;
  41919. _this._useSpecularOverAlpha = false;
  41920. _this._useReflectionOverAlpha = false;
  41921. _this._disableLighting = false;
  41922. _this._useObjectSpaceNormalMap = false;
  41923. _this._useParallax = false;
  41924. _this._useParallaxOcclusion = false;
  41925. _this.parallaxScaleBias = 0.05;
  41926. _this._roughness = 0;
  41927. _this.indexOfRefraction = 0.98;
  41928. _this.invertRefractionY = true;
  41929. /**
  41930. * Defines the alpha limits in alpha test mode
  41931. */
  41932. _this.alphaCutOff = 0.4;
  41933. _this._useLightmapAsShadowmap = false;
  41934. _this._useReflectionFresnelFromSpecular = false;
  41935. _this._useGlossinessFromSpecularMapAlpha = false;
  41936. _this._maxSimultaneousLights = 4;
  41937. /**
  41938. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41939. */
  41940. _this._invertNormalMapX = false;
  41941. /**
  41942. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41943. */
  41944. _this._invertNormalMapY = false;
  41945. /**
  41946. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41947. */
  41948. _this._twoSidedLighting = false;
  41949. _this._renderTargets = new BABYLON.SmartArray(16);
  41950. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41951. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41952. // Setup the default processing configuration to the scene.
  41953. _this._attachImageProcessingConfiguration(null);
  41954. _this.getRenderTargetTextures = function () {
  41955. _this._renderTargets.reset();
  41956. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41957. _this._renderTargets.push(_this._reflectionTexture);
  41958. }
  41959. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41960. _this._renderTargets.push(_this._refractionTexture);
  41961. }
  41962. return _this._renderTargets;
  41963. };
  41964. return _this;
  41965. }
  41966. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41967. /**
  41968. * Gets the image processing configuration used either in this material.
  41969. */
  41970. get: function () {
  41971. return this._imageProcessingConfiguration;
  41972. },
  41973. /**
  41974. * Sets the Default image processing configuration used either in the this material.
  41975. *
  41976. * If sets to null, the scene one is in use.
  41977. */
  41978. set: function (value) {
  41979. this._attachImageProcessingConfiguration(value);
  41980. // Ensure the effect will be rebuilt.
  41981. this._markAllSubMeshesAsTexturesDirty();
  41982. },
  41983. enumerable: true,
  41984. configurable: true
  41985. });
  41986. /**
  41987. * Attaches a new image processing configuration to the Standard Material.
  41988. * @param configuration
  41989. */
  41990. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41991. var _this = this;
  41992. if (configuration === this._imageProcessingConfiguration) {
  41993. return;
  41994. }
  41995. // Detaches observer.
  41996. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41997. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41998. }
  41999. // Pick the scene configuration if needed.
  42000. if (!configuration) {
  42001. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42002. }
  42003. else {
  42004. this._imageProcessingConfiguration = configuration;
  42005. }
  42006. // Attaches observer.
  42007. if (this._imageProcessingConfiguration) {
  42008. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42009. _this._markAllSubMeshesAsImageProcessingDirty();
  42010. });
  42011. }
  42012. };
  42013. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42014. /**
  42015. * Gets wether the color curves effect is enabled.
  42016. */
  42017. get: function () {
  42018. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42019. },
  42020. /**
  42021. * Sets wether the color curves effect is enabled.
  42022. */
  42023. set: function (value) {
  42024. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42025. },
  42026. enumerable: true,
  42027. configurable: true
  42028. });
  42029. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42030. /**
  42031. * Gets wether the color grading effect is enabled.
  42032. */
  42033. get: function () {
  42034. return this.imageProcessingConfiguration.colorGradingEnabled;
  42035. },
  42036. /**
  42037. * Gets wether the color grading effect is enabled.
  42038. */
  42039. set: function (value) {
  42040. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42041. },
  42042. enumerable: true,
  42043. configurable: true
  42044. });
  42045. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42046. /**
  42047. * Gets wether tonemapping is enabled or not.
  42048. */
  42049. get: function () {
  42050. return this._imageProcessingConfiguration.toneMappingEnabled;
  42051. },
  42052. /**
  42053. * Sets wether tonemapping is enabled or not
  42054. */
  42055. set: function (value) {
  42056. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42057. },
  42058. enumerable: true,
  42059. configurable: true
  42060. });
  42061. ;
  42062. ;
  42063. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42064. /**
  42065. * The camera exposure used on this material.
  42066. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42067. * This corresponds to a photographic exposure.
  42068. */
  42069. get: function () {
  42070. return this._imageProcessingConfiguration.exposure;
  42071. },
  42072. /**
  42073. * The camera exposure used on this material.
  42074. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42075. * This corresponds to a photographic exposure.
  42076. */
  42077. set: function (value) {
  42078. this._imageProcessingConfiguration.exposure = value;
  42079. },
  42080. enumerable: true,
  42081. configurable: true
  42082. });
  42083. ;
  42084. ;
  42085. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42086. /**
  42087. * Gets The camera contrast used on this material.
  42088. */
  42089. get: function () {
  42090. return this._imageProcessingConfiguration.contrast;
  42091. },
  42092. /**
  42093. * Sets The camera contrast used on this material.
  42094. */
  42095. set: function (value) {
  42096. this._imageProcessingConfiguration.contrast = value;
  42097. },
  42098. enumerable: true,
  42099. configurable: true
  42100. });
  42101. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42102. /**
  42103. * Gets the Color Grading 2D Lookup Texture.
  42104. */
  42105. get: function () {
  42106. return this._imageProcessingConfiguration.colorGradingTexture;
  42107. },
  42108. /**
  42109. * Sets the Color Grading 2D Lookup Texture.
  42110. */
  42111. set: function (value) {
  42112. this._imageProcessingConfiguration.colorGradingTexture = value;
  42113. },
  42114. enumerable: true,
  42115. configurable: true
  42116. });
  42117. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42118. /**
  42119. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42120. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42121. * 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;
  42122. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42123. */
  42124. get: function () {
  42125. return this._imageProcessingConfiguration.colorCurves;
  42126. },
  42127. /**
  42128. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42129. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42130. * 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;
  42131. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42132. */
  42133. set: function (value) {
  42134. this._imageProcessingConfiguration.colorCurves = value;
  42135. },
  42136. enumerable: true,
  42137. configurable: true
  42138. });
  42139. StandardMaterial.prototype.getClassName = function () {
  42140. return "StandardMaterial";
  42141. };
  42142. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42143. get: function () {
  42144. return this._useLogarithmicDepth;
  42145. },
  42146. set: function (value) {
  42147. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42148. this._markAllSubMeshesAsMiscDirty();
  42149. },
  42150. enumerable: true,
  42151. configurable: true
  42152. });
  42153. StandardMaterial.prototype.needAlphaBlending = function () {
  42154. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42155. };
  42156. StandardMaterial.prototype.needAlphaTesting = function () {
  42157. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42158. };
  42159. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42160. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42161. };
  42162. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42163. return this._diffuseTexture;
  42164. };
  42165. /**
  42166. * Child classes can use it to update shaders
  42167. */
  42168. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42169. if (useInstances === void 0) { useInstances = false; }
  42170. if (subMesh.effect && this.isFrozen) {
  42171. if (this._wasPreviouslyReady && subMesh.effect) {
  42172. return true;
  42173. }
  42174. }
  42175. if (!subMesh._materialDefines) {
  42176. subMesh._materialDefines = new StandardMaterialDefines();
  42177. }
  42178. var scene = this.getScene();
  42179. var defines = subMesh._materialDefines;
  42180. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42181. if (defines._renderId === scene.getRenderId()) {
  42182. return true;
  42183. }
  42184. }
  42185. var engine = scene.getEngine();
  42186. // Lights
  42187. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42188. // Textures
  42189. if (defines._areTexturesDirty) {
  42190. defines._needUVs = false;
  42191. defines.MAINUV1 = false;
  42192. defines.MAINUV2 = false;
  42193. if (scene.texturesEnabled) {
  42194. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42195. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42196. return false;
  42197. }
  42198. else {
  42199. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42200. }
  42201. }
  42202. else {
  42203. defines.DIFFUSE = false;
  42204. }
  42205. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42206. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42207. return false;
  42208. }
  42209. else {
  42210. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42211. }
  42212. }
  42213. else {
  42214. defines.AMBIENT = false;
  42215. }
  42216. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42217. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42218. return false;
  42219. }
  42220. else {
  42221. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42222. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42223. }
  42224. }
  42225. else {
  42226. defines.OPACITY = false;
  42227. }
  42228. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42229. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42230. return false;
  42231. }
  42232. else {
  42233. defines._needNormals = true;
  42234. defines.REFLECTION = true;
  42235. defines.ROUGHNESS = (this._roughness > 0);
  42236. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42237. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42238. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42239. switch (this._reflectionTexture.coordinatesMode) {
  42240. case BABYLON.Texture.EXPLICIT_MODE:
  42241. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42242. break;
  42243. case BABYLON.Texture.PLANAR_MODE:
  42244. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42245. break;
  42246. case BABYLON.Texture.PROJECTION_MODE:
  42247. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42248. break;
  42249. case BABYLON.Texture.SKYBOX_MODE:
  42250. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42251. break;
  42252. case BABYLON.Texture.SPHERICAL_MODE:
  42253. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42254. break;
  42255. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42256. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42257. break;
  42258. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42259. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42260. break;
  42261. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42262. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42263. break;
  42264. case BABYLON.Texture.CUBIC_MODE:
  42265. case BABYLON.Texture.INVCUBIC_MODE:
  42266. default:
  42267. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42268. break;
  42269. }
  42270. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42271. }
  42272. }
  42273. else {
  42274. defines.REFLECTION = false;
  42275. }
  42276. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42277. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42278. return false;
  42279. }
  42280. else {
  42281. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42282. }
  42283. }
  42284. else {
  42285. defines.EMISSIVE = false;
  42286. }
  42287. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42288. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42289. return false;
  42290. }
  42291. else {
  42292. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42293. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42294. }
  42295. }
  42296. else {
  42297. defines.LIGHTMAP = false;
  42298. }
  42299. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42300. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42301. return false;
  42302. }
  42303. else {
  42304. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42305. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42306. }
  42307. }
  42308. else {
  42309. defines.SPECULAR = false;
  42310. }
  42311. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42312. // Bump texure can not be not blocking.
  42313. if (!this._bumpTexture.isReady()) {
  42314. return false;
  42315. }
  42316. else {
  42317. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42318. defines.PARALLAX = this._useParallax;
  42319. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42320. }
  42321. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42322. }
  42323. else {
  42324. defines.BUMP = false;
  42325. }
  42326. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42327. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42328. return false;
  42329. }
  42330. else {
  42331. defines._needUVs = true;
  42332. defines.REFRACTION = true;
  42333. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42334. }
  42335. }
  42336. else {
  42337. defines.REFRACTION = false;
  42338. }
  42339. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42340. }
  42341. else {
  42342. defines.DIFFUSE = false;
  42343. defines.AMBIENT = false;
  42344. defines.OPACITY = false;
  42345. defines.REFLECTION = false;
  42346. defines.EMISSIVE = false;
  42347. defines.LIGHTMAP = false;
  42348. defines.BUMP = false;
  42349. defines.REFRACTION = false;
  42350. }
  42351. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42352. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42353. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42354. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42355. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42356. }
  42357. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42358. if (!this._imageProcessingConfiguration.isReady()) {
  42359. return false;
  42360. }
  42361. this._imageProcessingConfiguration.prepareDefines(defines);
  42362. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42363. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42364. }
  42365. if (defines._areFresnelDirty) {
  42366. if (StandardMaterial.FresnelEnabled) {
  42367. // Fresnel
  42368. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42369. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42370. this._reflectionFresnelParameters) {
  42371. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42372. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42373. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42374. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42375. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42376. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42377. defines._needNormals = true;
  42378. defines.FRESNEL = true;
  42379. }
  42380. }
  42381. else {
  42382. defines.FRESNEL = false;
  42383. }
  42384. }
  42385. // Misc.
  42386. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42387. // Attribs
  42388. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42389. // Values that need to be evaluated on every frame
  42390. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42391. // Get correct effect
  42392. if (defines.isDirty) {
  42393. defines.markAsProcessed();
  42394. scene.resetCachedMaterial();
  42395. // Fallbacks
  42396. var fallbacks = new BABYLON.EffectFallbacks();
  42397. if (defines.REFLECTION) {
  42398. fallbacks.addFallback(0, "REFLECTION");
  42399. }
  42400. if (defines.SPECULAR) {
  42401. fallbacks.addFallback(0, "SPECULAR");
  42402. }
  42403. if (defines.BUMP) {
  42404. fallbacks.addFallback(0, "BUMP");
  42405. }
  42406. if (defines.PARALLAX) {
  42407. fallbacks.addFallback(1, "PARALLAX");
  42408. }
  42409. if (defines.PARALLAXOCCLUSION) {
  42410. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42411. }
  42412. if (defines.SPECULAROVERALPHA) {
  42413. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42414. }
  42415. if (defines.FOG) {
  42416. fallbacks.addFallback(1, "FOG");
  42417. }
  42418. if (defines.POINTSIZE) {
  42419. fallbacks.addFallback(0, "POINTSIZE");
  42420. }
  42421. if (defines.LOGARITHMICDEPTH) {
  42422. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42423. }
  42424. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42425. if (defines.SPECULARTERM) {
  42426. fallbacks.addFallback(0, "SPECULARTERM");
  42427. }
  42428. if (defines.DIFFUSEFRESNEL) {
  42429. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42430. }
  42431. if (defines.OPACITYFRESNEL) {
  42432. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42433. }
  42434. if (defines.REFLECTIONFRESNEL) {
  42435. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42436. }
  42437. if (defines.EMISSIVEFRESNEL) {
  42438. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42439. }
  42440. if (defines.FRESNEL) {
  42441. fallbacks.addFallback(4, "FRESNEL");
  42442. }
  42443. //Attributes
  42444. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42445. if (defines.NORMAL) {
  42446. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42447. }
  42448. if (defines.UV1) {
  42449. attribs.push(BABYLON.VertexBuffer.UVKind);
  42450. }
  42451. if (defines.UV2) {
  42452. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42453. }
  42454. if (defines.VERTEXCOLOR) {
  42455. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42456. }
  42457. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42458. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42459. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42460. var shaderName = "default";
  42461. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42462. "vFogInfos", "vFogColor", "pointSize",
  42463. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42464. "mBones",
  42465. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42466. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42467. "vReflectionPosition", "vReflectionSize",
  42468. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42469. ];
  42470. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42471. var uniformBuffers = ["Material", "Scene"];
  42472. if (BABYLON.ImageProcessingConfiguration) {
  42473. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42474. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42475. }
  42476. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42477. uniformsNames: uniforms,
  42478. uniformBuffersNames: uniformBuffers,
  42479. samplers: samplers,
  42480. defines: defines,
  42481. maxSimultaneousLights: this._maxSimultaneousLights
  42482. });
  42483. if (this.customShaderNameResolve) {
  42484. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42485. }
  42486. var join = defines.toString();
  42487. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42488. attributes: attribs,
  42489. uniformsNames: uniforms,
  42490. uniformBuffersNames: uniformBuffers,
  42491. samplers: samplers,
  42492. defines: join,
  42493. fallbacks: fallbacks,
  42494. onCompiled: this.onCompiled,
  42495. onError: this.onError,
  42496. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42497. }, engine), defines);
  42498. this.buildUniformLayout();
  42499. }
  42500. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42501. return false;
  42502. }
  42503. defines._renderId = scene.getRenderId();
  42504. this._wasPreviouslyReady = true;
  42505. return true;
  42506. };
  42507. StandardMaterial.prototype.buildUniformLayout = function () {
  42508. // Order is important !
  42509. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42510. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42511. this._uniformBuffer.addUniform("opacityParts", 4);
  42512. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42513. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42514. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42515. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42516. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42517. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42518. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42519. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42520. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42521. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42522. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42523. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42524. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42525. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42526. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42527. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42528. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42529. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42530. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42531. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42532. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42533. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42534. this._uniformBuffer.addUniform("specularMatrix", 16);
  42535. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42536. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42537. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42538. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42539. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42540. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42541. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42542. this._uniformBuffer.addUniform("pointSize", 1);
  42543. this._uniformBuffer.create();
  42544. };
  42545. StandardMaterial.prototype.unbind = function () {
  42546. if (this._activeEffect) {
  42547. var needFlag = false;
  42548. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42549. this._activeEffect.setTexture("reflection2DSampler", null);
  42550. needFlag = true;
  42551. }
  42552. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42553. this._activeEffect.setTexture("refraction2DSampler", null);
  42554. needFlag = true;
  42555. }
  42556. if (needFlag) {
  42557. this._markAllSubMeshesAsTexturesDirty();
  42558. }
  42559. }
  42560. _super.prototype.unbind.call(this);
  42561. };
  42562. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42563. var scene = this.getScene();
  42564. var defines = subMesh._materialDefines;
  42565. if (!defines) {
  42566. return;
  42567. }
  42568. var effect = subMesh.effect;
  42569. if (!effect) {
  42570. return;
  42571. }
  42572. this._activeEffect = effect;
  42573. // Matrices
  42574. this.bindOnlyWorldMatrix(world);
  42575. // Normal Matrix
  42576. if (defines.OBJECTSPACE_NORMALMAP) {
  42577. world.toNormalMatrix(this._normalMatrix);
  42578. this.bindOnlyNormalMatrix(this._normalMatrix);
  42579. }
  42580. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42581. // Bones
  42582. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42583. if (mustRebind) {
  42584. this._uniformBuffer.bindToEffect(effect, "Material");
  42585. this.bindViewProjection(effect);
  42586. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42587. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42588. // Fresnel
  42589. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42590. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42591. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42592. }
  42593. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42594. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42595. }
  42596. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42597. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42598. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42599. }
  42600. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42601. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42602. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42603. }
  42604. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42605. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42606. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42607. }
  42608. }
  42609. // Textures
  42610. if (scene.texturesEnabled) {
  42611. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42612. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42613. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42614. if (this._diffuseTexture.hasAlpha) {
  42615. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42616. }
  42617. }
  42618. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42619. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42620. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42621. }
  42622. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42623. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42624. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42625. }
  42626. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42627. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42628. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42629. if (this._reflectionTexture.boundingBoxSize) {
  42630. var cubeTexture = this._reflectionTexture;
  42631. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42632. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42633. }
  42634. }
  42635. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42636. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42637. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42638. }
  42639. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42640. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42641. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42642. }
  42643. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42644. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42645. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42646. }
  42647. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42648. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42649. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42650. if (scene._mirroredCameraPosition) {
  42651. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42652. }
  42653. else {
  42654. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42655. }
  42656. }
  42657. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42658. var depth = 1.0;
  42659. if (!this._refractionTexture.isCube) {
  42660. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42661. if (this._refractionTexture.depth) {
  42662. depth = this._refractionTexture.depth;
  42663. }
  42664. }
  42665. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42666. }
  42667. }
  42668. // Point size
  42669. if (this.pointsCloud) {
  42670. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42671. }
  42672. if (defines.SPECULARTERM) {
  42673. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42674. }
  42675. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42676. // Diffuse
  42677. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42678. }
  42679. // Textures
  42680. if (scene.texturesEnabled) {
  42681. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42682. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42683. }
  42684. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42685. effect.setTexture("ambientSampler", this._ambientTexture);
  42686. }
  42687. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42688. effect.setTexture("opacitySampler", this._opacityTexture);
  42689. }
  42690. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42691. if (this._reflectionTexture.isCube) {
  42692. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42693. }
  42694. else {
  42695. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42696. }
  42697. }
  42698. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42699. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42700. }
  42701. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42702. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42703. }
  42704. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42705. effect.setTexture("specularSampler", this._specularTexture);
  42706. }
  42707. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42708. effect.setTexture("bumpSampler", this._bumpTexture);
  42709. }
  42710. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42711. var depth = 1.0;
  42712. if (this._refractionTexture.isCube) {
  42713. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42714. }
  42715. else {
  42716. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42717. }
  42718. }
  42719. }
  42720. // Clip plane
  42721. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42722. // Colors
  42723. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42724. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42725. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42726. }
  42727. if (mustRebind || !this.isFrozen) {
  42728. // Lights
  42729. if (scene.lightsEnabled && !this._disableLighting) {
  42730. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42731. }
  42732. // View
  42733. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42734. this.bindView(effect);
  42735. }
  42736. // Fog
  42737. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42738. // Morph targets
  42739. if (defines.NUM_MORPH_INFLUENCERS) {
  42740. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42741. }
  42742. // Log. depth
  42743. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42744. // image processing
  42745. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42746. this._imageProcessingConfiguration.bind(this._activeEffect);
  42747. }
  42748. }
  42749. this._uniformBuffer.update();
  42750. this._afterBind(mesh, this._activeEffect);
  42751. };
  42752. StandardMaterial.prototype.getAnimatables = function () {
  42753. var results = [];
  42754. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42755. results.push(this._diffuseTexture);
  42756. }
  42757. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42758. results.push(this._ambientTexture);
  42759. }
  42760. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42761. results.push(this._opacityTexture);
  42762. }
  42763. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42764. results.push(this._reflectionTexture);
  42765. }
  42766. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42767. results.push(this._emissiveTexture);
  42768. }
  42769. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42770. results.push(this._specularTexture);
  42771. }
  42772. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42773. results.push(this._bumpTexture);
  42774. }
  42775. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42776. results.push(this._lightmapTexture);
  42777. }
  42778. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42779. results.push(this._refractionTexture);
  42780. }
  42781. return results;
  42782. };
  42783. StandardMaterial.prototype.getActiveTextures = function () {
  42784. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42785. if (this._diffuseTexture) {
  42786. activeTextures.push(this._diffuseTexture);
  42787. }
  42788. if (this._ambientTexture) {
  42789. activeTextures.push(this._ambientTexture);
  42790. }
  42791. if (this._opacityTexture) {
  42792. activeTextures.push(this._opacityTexture);
  42793. }
  42794. if (this._reflectionTexture) {
  42795. activeTextures.push(this._reflectionTexture);
  42796. }
  42797. if (this._emissiveTexture) {
  42798. activeTextures.push(this._emissiveTexture);
  42799. }
  42800. if (this._specularTexture) {
  42801. activeTextures.push(this._specularTexture);
  42802. }
  42803. if (this._bumpTexture) {
  42804. activeTextures.push(this._bumpTexture);
  42805. }
  42806. if (this._lightmapTexture) {
  42807. activeTextures.push(this._lightmapTexture);
  42808. }
  42809. if (this._refractionTexture) {
  42810. activeTextures.push(this._refractionTexture);
  42811. }
  42812. return activeTextures;
  42813. };
  42814. StandardMaterial.prototype.hasTexture = function (texture) {
  42815. if (_super.prototype.hasTexture.call(this, texture)) {
  42816. return true;
  42817. }
  42818. if (this._diffuseTexture === texture) {
  42819. return true;
  42820. }
  42821. if (this._ambientTexture === texture) {
  42822. return true;
  42823. }
  42824. if (this._opacityTexture === texture) {
  42825. return true;
  42826. }
  42827. if (this._reflectionTexture === texture) {
  42828. return true;
  42829. }
  42830. if (this._emissiveTexture === texture) {
  42831. return true;
  42832. }
  42833. if (this._specularTexture === texture) {
  42834. return true;
  42835. }
  42836. if (this._bumpTexture === texture) {
  42837. return true;
  42838. }
  42839. if (this._lightmapTexture === texture) {
  42840. return true;
  42841. }
  42842. if (this._refractionTexture === texture) {
  42843. return true;
  42844. }
  42845. return false;
  42846. };
  42847. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42848. if (forceDisposeTextures) {
  42849. if (this._diffuseTexture) {
  42850. this._diffuseTexture.dispose();
  42851. }
  42852. if (this._ambientTexture) {
  42853. this._ambientTexture.dispose();
  42854. }
  42855. if (this._opacityTexture) {
  42856. this._opacityTexture.dispose();
  42857. }
  42858. if (this._reflectionTexture) {
  42859. this._reflectionTexture.dispose();
  42860. }
  42861. if (this._emissiveTexture) {
  42862. this._emissiveTexture.dispose();
  42863. }
  42864. if (this._specularTexture) {
  42865. this._specularTexture.dispose();
  42866. }
  42867. if (this._bumpTexture) {
  42868. this._bumpTexture.dispose();
  42869. }
  42870. if (this._lightmapTexture) {
  42871. this._lightmapTexture.dispose();
  42872. }
  42873. if (this._refractionTexture) {
  42874. this._refractionTexture.dispose();
  42875. }
  42876. }
  42877. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42878. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42879. }
  42880. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42881. };
  42882. StandardMaterial.prototype.clone = function (name) {
  42883. var _this = this;
  42884. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42885. result.name = name;
  42886. result.id = name;
  42887. return result;
  42888. };
  42889. StandardMaterial.prototype.serialize = function () {
  42890. return BABYLON.SerializationHelper.Serialize(this);
  42891. };
  42892. // Statics
  42893. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42894. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42895. };
  42896. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42897. get: function () {
  42898. return StandardMaterial._DiffuseTextureEnabled;
  42899. },
  42900. set: function (value) {
  42901. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42902. return;
  42903. }
  42904. StandardMaterial._DiffuseTextureEnabled = value;
  42905. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42906. },
  42907. enumerable: true,
  42908. configurable: true
  42909. });
  42910. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42911. get: function () {
  42912. return StandardMaterial._AmbientTextureEnabled;
  42913. },
  42914. set: function (value) {
  42915. if (StandardMaterial._AmbientTextureEnabled === value) {
  42916. return;
  42917. }
  42918. StandardMaterial._AmbientTextureEnabled = value;
  42919. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42920. },
  42921. enumerable: true,
  42922. configurable: true
  42923. });
  42924. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42925. get: function () {
  42926. return StandardMaterial._OpacityTextureEnabled;
  42927. },
  42928. set: function (value) {
  42929. if (StandardMaterial._OpacityTextureEnabled === value) {
  42930. return;
  42931. }
  42932. StandardMaterial._OpacityTextureEnabled = value;
  42933. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42934. },
  42935. enumerable: true,
  42936. configurable: true
  42937. });
  42938. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42939. get: function () {
  42940. return StandardMaterial._ReflectionTextureEnabled;
  42941. },
  42942. set: function (value) {
  42943. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42944. return;
  42945. }
  42946. StandardMaterial._ReflectionTextureEnabled = value;
  42947. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42948. },
  42949. enumerable: true,
  42950. configurable: true
  42951. });
  42952. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42953. get: function () {
  42954. return StandardMaterial._EmissiveTextureEnabled;
  42955. },
  42956. set: function (value) {
  42957. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42958. return;
  42959. }
  42960. StandardMaterial._EmissiveTextureEnabled = value;
  42961. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42962. },
  42963. enumerable: true,
  42964. configurable: true
  42965. });
  42966. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42967. get: function () {
  42968. return StandardMaterial._SpecularTextureEnabled;
  42969. },
  42970. set: function (value) {
  42971. if (StandardMaterial._SpecularTextureEnabled === value) {
  42972. return;
  42973. }
  42974. StandardMaterial._SpecularTextureEnabled = value;
  42975. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42976. },
  42977. enumerable: true,
  42978. configurable: true
  42979. });
  42980. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42981. get: function () {
  42982. return StandardMaterial._BumpTextureEnabled;
  42983. },
  42984. set: function (value) {
  42985. if (StandardMaterial._BumpTextureEnabled === value) {
  42986. return;
  42987. }
  42988. StandardMaterial._BumpTextureEnabled = value;
  42989. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42990. },
  42991. enumerable: true,
  42992. configurable: true
  42993. });
  42994. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42995. get: function () {
  42996. return StandardMaterial._LightmapTextureEnabled;
  42997. },
  42998. set: function (value) {
  42999. if (StandardMaterial._LightmapTextureEnabled === value) {
  43000. return;
  43001. }
  43002. StandardMaterial._LightmapTextureEnabled = value;
  43003. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43004. },
  43005. enumerable: true,
  43006. configurable: true
  43007. });
  43008. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43009. get: function () {
  43010. return StandardMaterial._RefractionTextureEnabled;
  43011. },
  43012. set: function (value) {
  43013. if (StandardMaterial._RefractionTextureEnabled === value) {
  43014. return;
  43015. }
  43016. StandardMaterial._RefractionTextureEnabled = value;
  43017. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43018. },
  43019. enumerable: true,
  43020. configurable: true
  43021. });
  43022. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43023. get: function () {
  43024. return StandardMaterial._ColorGradingTextureEnabled;
  43025. },
  43026. set: function (value) {
  43027. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43028. return;
  43029. }
  43030. StandardMaterial._ColorGradingTextureEnabled = value;
  43031. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43032. },
  43033. enumerable: true,
  43034. configurable: true
  43035. });
  43036. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43037. get: function () {
  43038. return StandardMaterial._FresnelEnabled;
  43039. },
  43040. set: function (value) {
  43041. if (StandardMaterial._FresnelEnabled === value) {
  43042. return;
  43043. }
  43044. StandardMaterial._FresnelEnabled = value;
  43045. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43046. },
  43047. enumerable: true,
  43048. configurable: true
  43049. });
  43050. // Flags used to enable or disable a type of texture for all Standard Materials
  43051. StandardMaterial._DiffuseTextureEnabled = true;
  43052. StandardMaterial._AmbientTextureEnabled = true;
  43053. StandardMaterial._OpacityTextureEnabled = true;
  43054. StandardMaterial._ReflectionTextureEnabled = true;
  43055. StandardMaterial._EmissiveTextureEnabled = true;
  43056. StandardMaterial._SpecularTextureEnabled = true;
  43057. StandardMaterial._BumpTextureEnabled = true;
  43058. StandardMaterial._LightmapTextureEnabled = true;
  43059. StandardMaterial._RefractionTextureEnabled = true;
  43060. StandardMaterial._ColorGradingTextureEnabled = true;
  43061. StandardMaterial._FresnelEnabled = true;
  43062. __decorate([
  43063. BABYLON.serializeAsTexture("diffuseTexture")
  43064. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43065. __decorate([
  43066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43067. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43068. __decorate([
  43069. BABYLON.serializeAsTexture("ambientTexture")
  43070. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43071. __decorate([
  43072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43073. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43074. __decorate([
  43075. BABYLON.serializeAsTexture("opacityTexture")
  43076. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43077. __decorate([
  43078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43079. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43080. __decorate([
  43081. BABYLON.serializeAsTexture("reflectionTexture")
  43082. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43083. __decorate([
  43084. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43085. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43086. __decorate([
  43087. BABYLON.serializeAsTexture("emissiveTexture")
  43088. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43089. __decorate([
  43090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43091. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43092. __decorate([
  43093. BABYLON.serializeAsTexture("specularTexture")
  43094. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43095. __decorate([
  43096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43097. ], StandardMaterial.prototype, "specularTexture", void 0);
  43098. __decorate([
  43099. BABYLON.serializeAsTexture("bumpTexture")
  43100. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43101. __decorate([
  43102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43103. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43104. __decorate([
  43105. BABYLON.serializeAsTexture("lightmapTexture")
  43106. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43107. __decorate([
  43108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43109. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43110. __decorate([
  43111. BABYLON.serializeAsTexture("refractionTexture")
  43112. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43113. __decorate([
  43114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43115. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43116. __decorate([
  43117. BABYLON.serializeAsColor3("ambient")
  43118. ], StandardMaterial.prototype, "ambientColor", void 0);
  43119. __decorate([
  43120. BABYLON.serializeAsColor3("diffuse")
  43121. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43122. __decorate([
  43123. BABYLON.serializeAsColor3("specular")
  43124. ], StandardMaterial.prototype, "specularColor", void 0);
  43125. __decorate([
  43126. BABYLON.serializeAsColor3("emissive")
  43127. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43128. __decorate([
  43129. BABYLON.serialize()
  43130. ], StandardMaterial.prototype, "specularPower", void 0);
  43131. __decorate([
  43132. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43133. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43134. __decorate([
  43135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43136. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43137. __decorate([
  43138. BABYLON.serialize("useEmissiveAsIllumination")
  43139. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43140. __decorate([
  43141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43142. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43143. __decorate([
  43144. BABYLON.serialize("linkEmissiveWithDiffuse")
  43145. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43146. __decorate([
  43147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43148. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43149. __decorate([
  43150. BABYLON.serialize("useSpecularOverAlpha")
  43151. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43152. __decorate([
  43153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43154. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43155. __decorate([
  43156. BABYLON.serialize("useReflectionOverAlpha")
  43157. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43158. __decorate([
  43159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43160. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43161. __decorate([
  43162. BABYLON.serialize("disableLighting")
  43163. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43164. __decorate([
  43165. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43166. ], StandardMaterial.prototype, "disableLighting", void 0);
  43167. __decorate([
  43168. BABYLON.serialize("useObjectSpaceNormalMap")
  43169. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43170. __decorate([
  43171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43172. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43173. __decorate([
  43174. BABYLON.serialize("useParallax")
  43175. ], StandardMaterial.prototype, "_useParallax", void 0);
  43176. __decorate([
  43177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43178. ], StandardMaterial.prototype, "useParallax", void 0);
  43179. __decorate([
  43180. BABYLON.serialize("useParallaxOcclusion")
  43181. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43182. __decorate([
  43183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43184. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43185. __decorate([
  43186. BABYLON.serialize()
  43187. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43188. __decorate([
  43189. BABYLON.serialize("roughness")
  43190. ], StandardMaterial.prototype, "_roughness", void 0);
  43191. __decorate([
  43192. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43193. ], StandardMaterial.prototype, "roughness", void 0);
  43194. __decorate([
  43195. BABYLON.serialize()
  43196. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43197. __decorate([
  43198. BABYLON.serialize()
  43199. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43200. __decorate([
  43201. BABYLON.serialize()
  43202. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43203. __decorate([
  43204. BABYLON.serialize("useLightmapAsShadowmap")
  43205. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43206. __decorate([
  43207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43208. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43209. __decorate([
  43210. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43211. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43212. __decorate([
  43213. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43214. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43215. __decorate([
  43216. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43217. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43218. __decorate([
  43219. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43220. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43221. __decorate([
  43222. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43223. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43224. __decorate([
  43225. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43226. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43227. __decorate([
  43228. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43229. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43230. __decorate([
  43231. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43232. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43233. __decorate([
  43234. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43235. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43236. __decorate([
  43237. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43238. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43239. __decorate([
  43240. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43241. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43242. __decorate([
  43243. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43244. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43245. __decorate([
  43246. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43247. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43248. __decorate([
  43249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43250. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43251. __decorate([
  43252. BABYLON.serialize("maxSimultaneousLights")
  43253. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43254. __decorate([
  43255. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43256. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43257. __decorate([
  43258. BABYLON.serialize("invertNormalMapX")
  43259. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43260. __decorate([
  43261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43262. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43263. __decorate([
  43264. BABYLON.serialize("invertNormalMapY")
  43265. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43266. __decorate([
  43267. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43268. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43269. __decorate([
  43270. BABYLON.serialize("twoSidedLighting")
  43271. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43272. __decorate([
  43273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43274. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43275. __decorate([
  43276. BABYLON.serialize()
  43277. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43278. return StandardMaterial;
  43279. }(BABYLON.PushMaterial));
  43280. BABYLON.StandardMaterial = StandardMaterial;
  43281. })(BABYLON || (BABYLON = {}));
  43282. //# sourceMappingURL=babylon.standardMaterial.js.map
  43283. var BABYLON;
  43284. (function (BABYLON) {
  43285. /**
  43286. * Manages the defines for the PBR Material.
  43287. * @hiddenChildren
  43288. */
  43289. var PBRMaterialDefines = /** @class */ (function (_super) {
  43290. __extends(PBRMaterialDefines, _super);
  43291. /**
  43292. * Initializes the PBR Material defines.
  43293. */
  43294. function PBRMaterialDefines() {
  43295. var _this = _super.call(this) || this;
  43296. _this.PBR = true;
  43297. _this.MAINUV1 = false;
  43298. _this.MAINUV2 = false;
  43299. _this.UV1 = false;
  43300. _this.UV2 = false;
  43301. _this.ALBEDO = false;
  43302. _this.ALBEDODIRECTUV = 0;
  43303. _this.VERTEXCOLOR = false;
  43304. _this.AMBIENT = false;
  43305. _this.AMBIENTDIRECTUV = 0;
  43306. _this.AMBIENTINGRAYSCALE = false;
  43307. _this.OPACITY = false;
  43308. _this.VERTEXALPHA = false;
  43309. _this.OPACITYDIRECTUV = 0;
  43310. _this.OPACITYRGB = false;
  43311. _this.ALPHATEST = false;
  43312. _this.DEPTHPREPASS = false;
  43313. _this.ALPHABLEND = false;
  43314. _this.ALPHAFROMALBEDO = false;
  43315. _this.ALPHATESTVALUE = "0.5";
  43316. _this.SPECULAROVERALPHA = false;
  43317. _this.RADIANCEOVERALPHA = false;
  43318. _this.ALPHAFRESNEL = false;
  43319. _this.LINEARALPHAFRESNEL = false;
  43320. _this.PREMULTIPLYALPHA = false;
  43321. _this.EMISSIVE = false;
  43322. _this.EMISSIVEDIRECTUV = 0;
  43323. _this.REFLECTIVITY = false;
  43324. _this.REFLECTIVITYDIRECTUV = 0;
  43325. _this.SPECULARTERM = false;
  43326. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43327. _this.MICROSURFACEAUTOMATIC = false;
  43328. _this.LODBASEDMICROSFURACE = false;
  43329. _this.MICROSURFACEMAP = false;
  43330. _this.MICROSURFACEMAPDIRECTUV = 0;
  43331. _this.METALLICWORKFLOW = false;
  43332. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43333. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43334. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43335. _this.AOSTOREINMETALMAPRED = false;
  43336. _this.ENVIRONMENTBRDF = false;
  43337. _this.NORMAL = false;
  43338. _this.TANGENT = false;
  43339. _this.BUMP = false;
  43340. _this.BUMPDIRECTUV = 0;
  43341. _this.OBJECTSPACE_NORMALMAP = false;
  43342. _this.PARALLAX = false;
  43343. _this.PARALLAXOCCLUSION = false;
  43344. _this.NORMALXYSCALE = true;
  43345. _this.LIGHTMAP = false;
  43346. _this.LIGHTMAPDIRECTUV = 0;
  43347. _this.USELIGHTMAPASSHADOWMAP = false;
  43348. _this.GAMMALIGHTMAP = false;
  43349. _this.REFLECTION = false;
  43350. _this.REFLECTIONMAP_3D = false;
  43351. _this.REFLECTIONMAP_SPHERICAL = false;
  43352. _this.REFLECTIONMAP_PLANAR = false;
  43353. _this.REFLECTIONMAP_CUBIC = false;
  43354. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43355. _this.REFLECTIONMAP_PROJECTION = false;
  43356. _this.REFLECTIONMAP_SKYBOX = false;
  43357. _this.REFLECTIONMAP_EXPLICIT = false;
  43358. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43359. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43360. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43361. _this.INVERTCUBICMAP = false;
  43362. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43363. _this.USESPHERICALINVERTEX = false;
  43364. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43365. _this.LODINREFLECTIONALPHA = false;
  43366. _this.GAMMAREFLECTION = false;
  43367. _this.RGBDREFLECTION = false;
  43368. _this.RADIANCEOCCLUSION = false;
  43369. _this.HORIZONOCCLUSION = false;
  43370. _this.REFRACTION = false;
  43371. _this.REFRACTIONMAP_3D = false;
  43372. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43373. _this.LODINREFRACTIONALPHA = false;
  43374. _this.GAMMAREFRACTION = false;
  43375. _this.RGBDREFRACTION = false;
  43376. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43377. _this.INSTANCES = false;
  43378. _this.NUM_BONE_INFLUENCERS = 0;
  43379. _this.BonesPerMesh = 0;
  43380. _this.NONUNIFORMSCALING = false;
  43381. _this.MORPHTARGETS = false;
  43382. _this.MORPHTARGETS_NORMAL = false;
  43383. _this.MORPHTARGETS_TANGENT = false;
  43384. _this.NUM_MORPH_INFLUENCERS = 0;
  43385. _this.IMAGEPROCESSING = false;
  43386. _this.VIGNETTE = false;
  43387. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43388. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43389. _this.TONEMAPPING = false;
  43390. _this.CONTRAST = false;
  43391. _this.COLORCURVES = false;
  43392. _this.COLORGRADING = false;
  43393. _this.COLORGRADING3D = false;
  43394. _this.SAMPLER3DGREENDEPTH = false;
  43395. _this.SAMPLER3DBGRMAP = false;
  43396. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43397. _this.EXPOSURE = false;
  43398. _this.USEPHYSICALLIGHTFALLOFF = false;
  43399. _this.TWOSIDEDLIGHTING = false;
  43400. _this.SHADOWFLOAT = false;
  43401. _this.CLIPPLANE = false;
  43402. _this.POINTSIZE = false;
  43403. _this.FOG = false;
  43404. _this.LOGARITHMICDEPTH = false;
  43405. _this.FORCENORMALFORWARD = false;
  43406. _this.SPECULARAA = false;
  43407. _this.UNLIT = false;
  43408. _this.rebuild();
  43409. return _this;
  43410. }
  43411. /**
  43412. * Resets the PBR Material defines.
  43413. */
  43414. PBRMaterialDefines.prototype.reset = function () {
  43415. _super.prototype.reset.call(this);
  43416. this.ALPHATESTVALUE = "0.5";
  43417. this.PBR = true;
  43418. };
  43419. return PBRMaterialDefines;
  43420. }(BABYLON.MaterialDefines));
  43421. /**
  43422. * The Physically based material base class of BJS.
  43423. *
  43424. * This offers the main features of a standard PBR material.
  43425. * For more information, please refer to the documentation :
  43426. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43427. */
  43428. var PBRBaseMaterial = /** @class */ (function (_super) {
  43429. __extends(PBRBaseMaterial, _super);
  43430. /**
  43431. * Instantiates a new PBRMaterial instance.
  43432. *
  43433. * @param name The material name
  43434. * @param scene The scene the material will be use in.
  43435. */
  43436. function PBRBaseMaterial(name, scene) {
  43437. var _this = _super.call(this, name, scene) || this;
  43438. /**
  43439. * Intensity of the direct lights e.g. the four lights available in your scene.
  43440. * This impacts both the direct diffuse and specular highlights.
  43441. */
  43442. _this._directIntensity = 1.0;
  43443. /**
  43444. * Intensity of the emissive part of the material.
  43445. * This helps controlling the emissive effect without modifying the emissive color.
  43446. */
  43447. _this._emissiveIntensity = 1.0;
  43448. /**
  43449. * Intensity of the environment e.g. how much the environment will light the object
  43450. * either through harmonics for rough material or through the refelction for shiny ones.
  43451. */
  43452. _this._environmentIntensity = 1.0;
  43453. /**
  43454. * This is a special control allowing the reduction of the specular highlights coming from the
  43455. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43456. */
  43457. _this._specularIntensity = 1.0;
  43458. /**
  43459. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43460. */
  43461. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43462. /**
  43463. * Debug Control allowing disabling the bump map on this material.
  43464. */
  43465. _this._disableBumpMap = false;
  43466. /**
  43467. * AKA Occlusion Texture Intensity in other nomenclature.
  43468. */
  43469. _this._ambientTextureStrength = 1.0;
  43470. /**
  43471. * The color of a material in ambient lighting.
  43472. */
  43473. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43474. /**
  43475. * AKA Diffuse Color in other nomenclature.
  43476. */
  43477. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43478. /**
  43479. * AKA Specular Color in other nomenclature.
  43480. */
  43481. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43482. /**
  43483. * The color applied when light is reflected from a material.
  43484. */
  43485. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43486. /**
  43487. * The color applied when light is emitted from a material.
  43488. */
  43489. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43490. /**
  43491. * AKA Glossiness in other nomenclature.
  43492. */
  43493. _this._microSurface = 0.9;
  43494. /**
  43495. * source material index of refraction (IOR)' / 'destination material IOR.
  43496. */
  43497. _this._indexOfRefraction = 0.66;
  43498. /**
  43499. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43500. */
  43501. _this._invertRefractionY = false;
  43502. /**
  43503. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43504. * Materials half opaque for instance using refraction could benefit from this control.
  43505. */
  43506. _this._linkRefractionWithTransparency = false;
  43507. /**
  43508. * Specifies that the material will use the light map as a show map.
  43509. */
  43510. _this._useLightmapAsShadowmap = false;
  43511. /**
  43512. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43513. * makes the reflect vector face the model (under horizon).
  43514. */
  43515. _this._useHorizonOcclusion = true;
  43516. /**
  43517. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43518. * too much the area relying on ambient texture to define their ambient occlusion.
  43519. */
  43520. _this._useRadianceOcclusion = true;
  43521. /**
  43522. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43523. */
  43524. _this._useAlphaFromAlbedoTexture = false;
  43525. /**
  43526. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43527. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43528. */
  43529. _this._useSpecularOverAlpha = true;
  43530. /**
  43531. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43532. */
  43533. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43534. /**
  43535. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43536. */
  43537. _this._useRoughnessFromMetallicTextureAlpha = true;
  43538. /**
  43539. * Specifies if the metallic texture contains the roughness information in its green channel.
  43540. */
  43541. _this._useRoughnessFromMetallicTextureGreen = false;
  43542. /**
  43543. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43544. */
  43545. _this._useMetallnessFromMetallicTextureBlue = false;
  43546. /**
  43547. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43548. */
  43549. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43550. /**
  43551. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43552. */
  43553. _this._useAmbientInGrayScale = false;
  43554. /**
  43555. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43556. * The material will try to infer what glossiness each pixel should be.
  43557. */
  43558. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43559. /**
  43560. * BJS is using an harcoded light falloff based on a manually sets up range.
  43561. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43562. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43563. */
  43564. _this._usePhysicalLightFalloff = true;
  43565. /**
  43566. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43567. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43568. */
  43569. _this._useRadianceOverAlpha = true;
  43570. /**
  43571. * Allows using an object space normal map (instead of tangent space).
  43572. */
  43573. _this._useObjectSpaceNormalMap = false;
  43574. /**
  43575. * Allows using the bump map in parallax mode.
  43576. */
  43577. _this._useParallax = false;
  43578. /**
  43579. * Allows using the bump map in parallax occlusion mode.
  43580. */
  43581. _this._useParallaxOcclusion = false;
  43582. /**
  43583. * Controls the scale bias of the parallax mode.
  43584. */
  43585. _this._parallaxScaleBias = 0.05;
  43586. /**
  43587. * If sets to true, disables all the lights affecting the material.
  43588. */
  43589. _this._disableLighting = false;
  43590. /**
  43591. * Number of Simultaneous lights allowed on the material.
  43592. */
  43593. _this._maxSimultaneousLights = 4;
  43594. /**
  43595. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43596. */
  43597. _this._invertNormalMapX = false;
  43598. /**
  43599. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43600. */
  43601. _this._invertNormalMapY = false;
  43602. /**
  43603. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43604. */
  43605. _this._twoSidedLighting = false;
  43606. /**
  43607. * Defines the alpha limits in alpha test mode.
  43608. */
  43609. _this._alphaCutOff = 0.4;
  43610. /**
  43611. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43612. */
  43613. _this._forceAlphaTest = false;
  43614. /**
  43615. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43616. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43617. */
  43618. _this._useAlphaFresnel = false;
  43619. /**
  43620. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43621. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43622. */
  43623. _this._useLinearAlphaFresnel = false;
  43624. /**
  43625. * The transparency mode of the material.
  43626. */
  43627. _this._transparencyMode = null;
  43628. /**
  43629. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43630. * from cos thetav and roughness:
  43631. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43632. */
  43633. _this._environmentBRDFTexture = null;
  43634. /**
  43635. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43636. */
  43637. _this._forceIrradianceInFragment = false;
  43638. /**
  43639. * Force normal to face away from face.
  43640. */
  43641. _this._forceNormalForward = false;
  43642. /**
  43643. * Enables specular anti aliasing in the PBR shader.
  43644. * It will both interacts on the Geometry for analytical and IBL lighting.
  43645. * It also prefilter the roughness map based on the bump values.
  43646. */
  43647. _this._enableSpecularAntiAliasing = false;
  43648. /**
  43649. * Stores the available render targets.
  43650. */
  43651. _this._renderTargets = new BABYLON.SmartArray(16);
  43652. /**
  43653. * Sets the global ambient color for the material used in lighting calculations.
  43654. */
  43655. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43656. /**
  43657. * If set to true, no lighting calculations will be applied.
  43658. */
  43659. _this._unlit = false;
  43660. // Setup the default processing configuration to the scene.
  43661. _this._attachImageProcessingConfiguration(null);
  43662. _this.getRenderTargetTextures = function () {
  43663. _this._renderTargets.reset();
  43664. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43665. _this._renderTargets.push(_this._reflectionTexture);
  43666. }
  43667. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43668. _this._renderTargets.push(_this._refractionTexture);
  43669. }
  43670. return _this._renderTargets;
  43671. };
  43672. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43673. return _this;
  43674. }
  43675. /**
  43676. * Attaches a new image processing configuration to the PBR Material.
  43677. * @param configuration
  43678. */
  43679. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43680. var _this = this;
  43681. if (configuration === this._imageProcessingConfiguration) {
  43682. return;
  43683. }
  43684. // Detaches observer.
  43685. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43686. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43687. }
  43688. // Pick the scene configuration if needed.
  43689. if (!configuration) {
  43690. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43691. }
  43692. else {
  43693. this._imageProcessingConfiguration = configuration;
  43694. }
  43695. // Attaches observer.
  43696. if (this._imageProcessingConfiguration) {
  43697. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43698. _this._markAllSubMeshesAsImageProcessingDirty();
  43699. });
  43700. }
  43701. };
  43702. /**
  43703. * Gets the name of the material class.
  43704. */
  43705. PBRBaseMaterial.prototype.getClassName = function () {
  43706. return "PBRBaseMaterial";
  43707. };
  43708. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43709. /**
  43710. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43711. */
  43712. get: function () {
  43713. return this._useLogarithmicDepth;
  43714. },
  43715. /**
  43716. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43717. */
  43718. set: function (value) {
  43719. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43720. },
  43721. enumerable: true,
  43722. configurable: true
  43723. });
  43724. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43725. /**
  43726. * Gets the current transparency mode.
  43727. */
  43728. get: function () {
  43729. return this._transparencyMode;
  43730. },
  43731. /**
  43732. * Sets the transparency mode of the material.
  43733. *
  43734. * | Value | Type | Description |
  43735. * | ----- | ----------------------------------- | ----------- |
  43736. * | 0 | OPAQUE | |
  43737. * | 1 | ALPHATEST | |
  43738. * | 2 | ALPHABLEND | |
  43739. * | 3 | ALPHATESTANDBLEND | |
  43740. *
  43741. */
  43742. set: function (value) {
  43743. if (this._transparencyMode === value) {
  43744. return;
  43745. }
  43746. this._transparencyMode = value;
  43747. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43748. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43749. },
  43750. enumerable: true,
  43751. configurable: true
  43752. });
  43753. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43754. /**
  43755. * Returns true if alpha blending should be disabled.
  43756. */
  43757. get: function () {
  43758. return (this._linkRefractionWithTransparency ||
  43759. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43760. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43761. },
  43762. enumerable: true,
  43763. configurable: true
  43764. });
  43765. /**
  43766. * Specifies whether or not this material should be rendered in alpha blend mode.
  43767. */
  43768. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43769. if (this._disableAlphaBlending) {
  43770. return false;
  43771. }
  43772. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43773. };
  43774. /**
  43775. * Specifies if the mesh will require alpha blending.
  43776. * @param mesh - BJS mesh.
  43777. */
  43778. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43779. if (this._disableAlphaBlending) {
  43780. return false;
  43781. }
  43782. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43783. };
  43784. /**
  43785. * Specifies whether or not this material should be rendered in alpha test mode.
  43786. */
  43787. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43788. if (this._forceAlphaTest) {
  43789. return true;
  43790. }
  43791. if (this._linkRefractionWithTransparency) {
  43792. return false;
  43793. }
  43794. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43795. };
  43796. /**
  43797. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43798. */
  43799. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43800. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43801. };
  43802. /**
  43803. * Gets the texture used for the alpha test.
  43804. */
  43805. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43806. return this._albedoTexture;
  43807. };
  43808. /**
  43809. * Specifies that the submesh is ready to be used.
  43810. * @param mesh - BJS mesh.
  43811. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43812. * @param useInstances - Specifies that instances should be used.
  43813. * @returns - boolean indicating that the submesh is ready or not.
  43814. */
  43815. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43816. if (subMesh.effect && this.isFrozen) {
  43817. if (this._wasPreviouslyReady) {
  43818. return true;
  43819. }
  43820. }
  43821. if (!subMesh._materialDefines) {
  43822. subMesh._materialDefines = new PBRMaterialDefines();
  43823. }
  43824. var defines = subMesh._materialDefines;
  43825. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43826. if (defines._renderId === this.getScene().getRenderId()) {
  43827. return true;
  43828. }
  43829. }
  43830. var scene = this.getScene();
  43831. var engine = scene.getEngine();
  43832. if (defines._areTexturesDirty) {
  43833. if (scene.texturesEnabled) {
  43834. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43835. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43836. return false;
  43837. }
  43838. }
  43839. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43840. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43841. return false;
  43842. }
  43843. }
  43844. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43845. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43846. return false;
  43847. }
  43848. }
  43849. var reflectionTexture = this._getReflectionTexture();
  43850. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43851. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43852. return false;
  43853. }
  43854. }
  43855. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43856. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43857. return false;
  43858. }
  43859. }
  43860. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43861. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43862. return false;
  43863. }
  43864. }
  43865. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43866. if (this._metallicTexture) {
  43867. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43868. return false;
  43869. }
  43870. }
  43871. else if (this._reflectivityTexture) {
  43872. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43873. return false;
  43874. }
  43875. }
  43876. if (this._microSurfaceTexture) {
  43877. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43878. return false;
  43879. }
  43880. }
  43881. }
  43882. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43883. // Bump texture cannot be not blocking.
  43884. if (!this._bumpTexture.isReady()) {
  43885. return false;
  43886. }
  43887. }
  43888. var refractionTexture = this._getRefractionTexture();
  43889. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43890. if (!refractionTexture.isReadyOrNotBlocking()) {
  43891. return false;
  43892. }
  43893. }
  43894. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43895. // This is blocking.
  43896. if (!this._environmentBRDFTexture.isReady()) {
  43897. return false;
  43898. }
  43899. }
  43900. }
  43901. }
  43902. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43903. if (!this._imageProcessingConfiguration.isReady()) {
  43904. return false;
  43905. }
  43906. }
  43907. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43908. mesh.createNormals(true);
  43909. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43910. }
  43911. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43912. if (effect) {
  43913. scene.resetCachedMaterial();
  43914. subMesh.setEffect(effect, defines);
  43915. this.buildUniformLayout();
  43916. }
  43917. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43918. return false;
  43919. }
  43920. defines._renderId = scene.getRenderId();
  43921. this._wasPreviouslyReady = true;
  43922. return true;
  43923. };
  43924. /**
  43925. * Specifies if the material uses metallic roughness workflow.
  43926. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43927. */
  43928. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43929. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43930. return true;
  43931. }
  43932. return false;
  43933. };
  43934. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43935. if (onCompiled === void 0) { onCompiled = null; }
  43936. if (onError === void 0) { onError = null; }
  43937. if (useInstances === void 0) { useInstances = null; }
  43938. if (useClipPlane === void 0) { useClipPlane = null; }
  43939. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43940. if (!defines.isDirty) {
  43941. return null;
  43942. }
  43943. defines.markAsProcessed();
  43944. var scene = this.getScene();
  43945. var engine = scene.getEngine();
  43946. // Fallbacks
  43947. var fallbacks = new BABYLON.EffectFallbacks();
  43948. var fallbackRank = 0;
  43949. if (defines.USESPHERICALINVERTEX) {
  43950. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43951. }
  43952. if (defines.FOG) {
  43953. fallbacks.addFallback(fallbackRank, "FOG");
  43954. }
  43955. if (defines.SPECULARAA) {
  43956. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43957. }
  43958. if (defines.POINTSIZE) {
  43959. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43960. }
  43961. if (defines.LOGARITHMICDEPTH) {
  43962. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43963. }
  43964. if (defines.PARALLAX) {
  43965. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43966. }
  43967. if (defines.PARALLAXOCCLUSION) {
  43968. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43969. }
  43970. if (defines.ENVIRONMENTBRDF) {
  43971. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43972. }
  43973. if (defines.TANGENT) {
  43974. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43975. }
  43976. if (defines.BUMP) {
  43977. fallbacks.addFallback(fallbackRank++, "BUMP");
  43978. }
  43979. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43980. if (defines.SPECULARTERM) {
  43981. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43982. }
  43983. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43984. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43985. }
  43986. if (defines.LIGHTMAP) {
  43987. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43988. }
  43989. if (defines.NORMAL) {
  43990. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43991. }
  43992. if (defines.AMBIENT) {
  43993. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43994. }
  43995. if (defines.EMISSIVE) {
  43996. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43997. }
  43998. if (defines.VERTEXCOLOR) {
  43999. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44000. }
  44001. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44002. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44003. }
  44004. if (defines.MORPHTARGETS) {
  44005. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44006. }
  44007. //Attributes
  44008. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44009. if (defines.NORMAL) {
  44010. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44011. }
  44012. if (defines.TANGENT) {
  44013. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44014. }
  44015. if (defines.UV1) {
  44016. attribs.push(BABYLON.VertexBuffer.UVKind);
  44017. }
  44018. if (defines.UV2) {
  44019. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44020. }
  44021. if (defines.VERTEXCOLOR) {
  44022. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44023. }
  44024. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44025. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44026. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44027. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44028. "vFogInfos", "vFogColor", "pointSize",
  44029. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44030. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44031. "mBones",
  44032. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44033. "vLightingIntensity",
  44034. "logarithmicDepthConstant",
  44035. "vSphericalX", "vSphericalY", "vSphericalZ",
  44036. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44037. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44038. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44039. "vTangentSpaceParams"
  44040. ];
  44041. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44042. "bumpSampler", "lightmapSampler", "opacitySampler",
  44043. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44044. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44045. "microSurfaceSampler", "environmentBrdfSampler"];
  44046. var uniformBuffers = ["Material", "Scene"];
  44047. if (BABYLON.ImageProcessingConfiguration) {
  44048. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44049. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44050. }
  44051. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44052. uniformsNames: uniforms,
  44053. uniformBuffersNames: uniformBuffers,
  44054. samplers: samplers,
  44055. defines: defines,
  44056. maxSimultaneousLights: this._maxSimultaneousLights
  44057. });
  44058. var join = defines.toString();
  44059. return engine.createEffect("pbr", {
  44060. attributes: attribs,
  44061. uniformsNames: uniforms,
  44062. uniformBuffersNames: uniformBuffers,
  44063. samplers: samplers,
  44064. defines: join,
  44065. fallbacks: fallbacks,
  44066. onCompiled: onCompiled,
  44067. onError: onError,
  44068. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44069. }, engine);
  44070. };
  44071. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44072. if (useInstances === void 0) { useInstances = null; }
  44073. if (useClipPlane === void 0) { useClipPlane = null; }
  44074. var scene = this.getScene();
  44075. var engine = scene.getEngine();
  44076. // Lights
  44077. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44078. defines._needNormals = true;
  44079. // Textures
  44080. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44081. if (defines._areTexturesDirty) {
  44082. defines._needUVs = false;
  44083. if (scene.texturesEnabled) {
  44084. if (scene.getEngine().getCaps().textureLOD) {
  44085. defines.LODBASEDMICROSFURACE = true;
  44086. }
  44087. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44088. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44089. }
  44090. else {
  44091. defines.ALBEDO = false;
  44092. }
  44093. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44094. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44095. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44096. }
  44097. else {
  44098. defines.AMBIENT = false;
  44099. }
  44100. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44101. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44102. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44103. }
  44104. else {
  44105. defines.OPACITY = false;
  44106. }
  44107. var reflectionTexture = this._getReflectionTexture();
  44108. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44109. defines.REFLECTION = true;
  44110. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44111. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44112. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44113. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44114. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44115. defines.INVERTCUBICMAP = true;
  44116. }
  44117. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44118. switch (reflectionTexture.coordinatesMode) {
  44119. case BABYLON.Texture.EXPLICIT_MODE:
  44120. defines.REFLECTIONMAP_EXPLICIT = true;
  44121. break;
  44122. case BABYLON.Texture.PLANAR_MODE:
  44123. defines.REFLECTIONMAP_PLANAR = true;
  44124. break;
  44125. case BABYLON.Texture.PROJECTION_MODE:
  44126. defines.REFLECTIONMAP_PROJECTION = true;
  44127. break;
  44128. case BABYLON.Texture.SKYBOX_MODE:
  44129. defines.REFLECTIONMAP_SKYBOX = true;
  44130. break;
  44131. case BABYLON.Texture.SPHERICAL_MODE:
  44132. defines.REFLECTIONMAP_SPHERICAL = true;
  44133. break;
  44134. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44135. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44136. break;
  44137. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44138. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44139. break;
  44140. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44141. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44142. break;
  44143. case BABYLON.Texture.CUBIC_MODE:
  44144. case BABYLON.Texture.INVCUBIC_MODE:
  44145. default:
  44146. defines.REFLECTIONMAP_CUBIC = true;
  44147. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44148. break;
  44149. }
  44150. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44151. if (reflectionTexture.sphericalPolynomial) {
  44152. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44153. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44154. defines.USESPHERICALINVERTEX = false;
  44155. }
  44156. else {
  44157. defines.USESPHERICALINVERTEX = true;
  44158. }
  44159. }
  44160. }
  44161. }
  44162. else {
  44163. defines.REFLECTION = false;
  44164. defines.REFLECTIONMAP_3D = false;
  44165. defines.REFLECTIONMAP_SPHERICAL = false;
  44166. defines.REFLECTIONMAP_PLANAR = false;
  44167. defines.REFLECTIONMAP_CUBIC = false;
  44168. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44169. defines.REFLECTIONMAP_PROJECTION = false;
  44170. defines.REFLECTIONMAP_SKYBOX = false;
  44171. defines.REFLECTIONMAP_EXPLICIT = false;
  44172. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44173. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44174. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44175. defines.INVERTCUBICMAP = false;
  44176. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44177. defines.USESPHERICALINVERTEX = false;
  44178. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44179. defines.LODINREFLECTIONALPHA = false;
  44180. defines.GAMMAREFLECTION = false;
  44181. defines.RGBDREFLECTION = false;
  44182. }
  44183. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44184. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44185. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44186. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44187. }
  44188. else {
  44189. defines.LIGHTMAP = false;
  44190. }
  44191. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44192. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44193. }
  44194. else {
  44195. defines.EMISSIVE = false;
  44196. }
  44197. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44198. if (this._metallicTexture) {
  44199. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44200. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44201. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44202. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44203. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44204. }
  44205. else if (this._reflectivityTexture) {
  44206. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44207. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44208. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44209. }
  44210. else {
  44211. defines.REFLECTIVITY = false;
  44212. }
  44213. if (this._microSurfaceTexture) {
  44214. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44215. }
  44216. else {
  44217. defines.MICROSURFACEMAP = false;
  44218. }
  44219. }
  44220. else {
  44221. defines.REFLECTIVITY = false;
  44222. defines.MICROSURFACEMAP = false;
  44223. }
  44224. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44225. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44226. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44227. defines.PARALLAX = true;
  44228. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44229. }
  44230. else {
  44231. defines.PARALLAX = false;
  44232. }
  44233. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44234. }
  44235. else {
  44236. defines.BUMP = false;
  44237. }
  44238. var refractionTexture = this._getRefractionTexture();
  44239. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44240. defines.REFRACTION = true;
  44241. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44242. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44243. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44244. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44245. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44246. if (this._linkRefractionWithTransparency) {
  44247. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44248. }
  44249. }
  44250. else {
  44251. defines.REFRACTION = false;
  44252. }
  44253. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44254. defines.ENVIRONMENTBRDF = true;
  44255. }
  44256. else {
  44257. defines.ENVIRONMENTBRDF = false;
  44258. }
  44259. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44260. defines.ALPHAFROMALBEDO = true;
  44261. }
  44262. else {
  44263. defines.ALPHAFROMALBEDO = false;
  44264. }
  44265. }
  44266. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44267. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44268. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44269. if (!this.backFaceCulling && this._twoSidedLighting) {
  44270. defines.TWOSIDEDLIGHTING = true;
  44271. }
  44272. else {
  44273. defines.TWOSIDEDLIGHTING = false;
  44274. }
  44275. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44276. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44277. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44278. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44279. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44280. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44281. }
  44282. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44283. this._imageProcessingConfiguration.prepareDefines(defines);
  44284. }
  44285. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44286. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44287. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44288. // Misc.
  44289. if (defines._areMiscDirty) {
  44290. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44291. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44292. }
  44293. // Values that need to be evaluated on every frame
  44294. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44295. // Attribs
  44296. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44297. };
  44298. /**
  44299. * Force shader compilation
  44300. */
  44301. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44302. var _this = this;
  44303. var localOptions = __assign({ clipPlane: false }, options);
  44304. var defines = new PBRMaterialDefines();
  44305. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44306. if (effect.isReady()) {
  44307. if (onCompiled) {
  44308. onCompiled(this);
  44309. }
  44310. }
  44311. else {
  44312. effect.onCompileObservable.add(function () {
  44313. if (onCompiled) {
  44314. onCompiled(_this);
  44315. }
  44316. });
  44317. }
  44318. };
  44319. /**
  44320. * Initializes the uniform buffer layout for the shader.
  44321. */
  44322. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44323. // Order is important !
  44324. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44325. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44326. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44327. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44328. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44329. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44330. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44331. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44332. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44333. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44334. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44335. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44336. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44337. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44338. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44339. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44340. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44341. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44342. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44343. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44344. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44345. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44346. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44347. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44348. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44349. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44350. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44351. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44352. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44353. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44354. this._uniformBuffer.addUniform("pointSize", 1);
  44355. this._uniformBuffer.create();
  44356. };
  44357. /**
  44358. * Unbinds the textures.
  44359. */
  44360. PBRBaseMaterial.prototype.unbind = function () {
  44361. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44362. this._uniformBuffer.setTexture("reflectionSampler", null);
  44363. }
  44364. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44365. this._uniformBuffer.setTexture("refractionSampler", null);
  44366. }
  44367. _super.prototype.unbind.call(this);
  44368. };
  44369. /**
  44370. * Binds the submesh data.
  44371. * @param world - The world matrix.
  44372. * @param mesh - The BJS mesh.
  44373. * @param subMesh - A submesh of the BJS mesh.
  44374. */
  44375. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44376. var scene = this.getScene();
  44377. var defines = subMesh._materialDefines;
  44378. if (!defines) {
  44379. return;
  44380. }
  44381. var effect = subMesh.effect;
  44382. if (!effect) {
  44383. return;
  44384. }
  44385. this._activeEffect = effect;
  44386. // Matrices
  44387. this.bindOnlyWorldMatrix(world);
  44388. // Normal Matrix
  44389. if (defines.OBJECTSPACE_NORMALMAP) {
  44390. world.toNormalMatrix(this._normalMatrix);
  44391. this.bindOnlyNormalMatrix(this._normalMatrix);
  44392. }
  44393. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44394. // Bones
  44395. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44396. var reflectionTexture = null;
  44397. if (mustRebind) {
  44398. this._uniformBuffer.bindToEffect(effect, "Material");
  44399. this.bindViewProjection(effect);
  44400. reflectionTexture = this._getReflectionTexture();
  44401. var refractionTexture = this._getRefractionTexture();
  44402. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44403. // Texture uniforms
  44404. if (scene.texturesEnabled) {
  44405. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44406. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44407. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44408. }
  44409. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44410. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44411. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44412. }
  44413. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44414. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44415. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44416. }
  44417. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44418. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44419. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44420. if (reflectionTexture.boundingBoxSize) {
  44421. var cubeTexture = reflectionTexture;
  44422. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44423. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44424. }
  44425. var polynomials = reflectionTexture.sphericalPolynomial;
  44426. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44427. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44428. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44429. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44430. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44431. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44432. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44433. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44434. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44435. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44436. }
  44437. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44438. }
  44439. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44440. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44441. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44442. }
  44443. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44444. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44445. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44446. }
  44447. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44448. if (this._metallicTexture) {
  44449. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44450. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44451. }
  44452. else if (this._reflectivityTexture) {
  44453. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44454. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44455. }
  44456. if (this._microSurfaceTexture) {
  44457. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44458. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44459. }
  44460. }
  44461. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44462. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44463. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44464. if (scene._mirroredCameraPosition) {
  44465. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44466. }
  44467. else {
  44468. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44469. }
  44470. }
  44471. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44472. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44473. var depth = 1.0;
  44474. if (!refractionTexture.isCube) {
  44475. if (refractionTexture.depth) {
  44476. depth = refractionTexture.depth;
  44477. }
  44478. }
  44479. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44480. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44481. }
  44482. }
  44483. // Point size
  44484. if (this.pointsCloud) {
  44485. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44486. }
  44487. // Colors
  44488. if (defines.METALLICWORKFLOW) {
  44489. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44490. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44491. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44492. }
  44493. else {
  44494. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44495. }
  44496. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44497. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44498. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44499. // Misc
  44500. this._lightingInfos.x = this._directIntensity;
  44501. this._lightingInfos.y = this._emissiveIntensity;
  44502. this._lightingInfos.z = this._environmentIntensity;
  44503. this._lightingInfos.w = this._specularIntensity;
  44504. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44505. }
  44506. // Textures
  44507. if (scene.texturesEnabled) {
  44508. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44509. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44510. }
  44511. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44512. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44513. }
  44514. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44515. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44516. }
  44517. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44518. if (defines.LODBASEDMICROSFURACE) {
  44519. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44520. }
  44521. else {
  44522. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44523. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44524. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44525. }
  44526. }
  44527. if (defines.ENVIRONMENTBRDF) {
  44528. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44529. }
  44530. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44531. if (defines.LODBASEDMICROSFURACE) {
  44532. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44533. }
  44534. else {
  44535. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44536. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44537. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44538. }
  44539. }
  44540. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44541. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44542. }
  44543. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44544. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44545. }
  44546. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44547. if (this._metallicTexture) {
  44548. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44549. }
  44550. else if (this._reflectivityTexture) {
  44551. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44552. }
  44553. if (this._microSurfaceTexture) {
  44554. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44555. }
  44556. }
  44557. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44558. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44559. }
  44560. }
  44561. // Clip plane
  44562. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44563. // Colors
  44564. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44565. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44566. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44567. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44568. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44569. }
  44570. if (mustRebind || !this.isFrozen) {
  44571. // Lights
  44572. if (scene.lightsEnabled && !this._disableLighting) {
  44573. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44574. }
  44575. // View
  44576. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44577. this.bindView(effect);
  44578. }
  44579. // Fog
  44580. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44581. // Morph targets
  44582. if (defines.NUM_MORPH_INFLUENCERS) {
  44583. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44584. }
  44585. // image processing
  44586. this._imageProcessingConfiguration.bind(this._activeEffect);
  44587. // Log. depth
  44588. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44589. }
  44590. this._uniformBuffer.update();
  44591. this._afterBind(mesh, this._activeEffect);
  44592. };
  44593. /**
  44594. * Returns the animatable textures.
  44595. * @returns - Array of animatable textures.
  44596. */
  44597. PBRBaseMaterial.prototype.getAnimatables = function () {
  44598. var results = [];
  44599. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44600. results.push(this._albedoTexture);
  44601. }
  44602. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44603. results.push(this._ambientTexture);
  44604. }
  44605. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44606. results.push(this._opacityTexture);
  44607. }
  44608. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44609. results.push(this._reflectionTexture);
  44610. }
  44611. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44612. results.push(this._emissiveTexture);
  44613. }
  44614. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44615. results.push(this._metallicTexture);
  44616. }
  44617. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44618. results.push(this._reflectivityTexture);
  44619. }
  44620. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44621. results.push(this._bumpTexture);
  44622. }
  44623. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44624. results.push(this._lightmapTexture);
  44625. }
  44626. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44627. results.push(this._refractionTexture);
  44628. }
  44629. return results;
  44630. };
  44631. /**
  44632. * Returns the texture used for reflections.
  44633. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44634. */
  44635. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44636. if (this._reflectionTexture) {
  44637. return this._reflectionTexture;
  44638. }
  44639. return this.getScene().environmentTexture;
  44640. };
  44641. /**
  44642. * Returns the texture used for refraction or null if none is used.
  44643. * @returns - Refection texture if present. If no refraction texture and refraction
  44644. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44645. */
  44646. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44647. if (this._refractionTexture) {
  44648. return this._refractionTexture;
  44649. }
  44650. if (this._linkRefractionWithTransparency) {
  44651. return this.getScene().environmentTexture;
  44652. }
  44653. return null;
  44654. };
  44655. /**
  44656. * Disposes the resources of the material.
  44657. * @param forceDisposeEffect - Forces the disposal of effects.
  44658. * @param forceDisposeTextures - Forces the disposal of all textures.
  44659. */
  44660. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44661. if (forceDisposeTextures) {
  44662. if (this._albedoTexture) {
  44663. this._albedoTexture.dispose();
  44664. }
  44665. if (this._ambientTexture) {
  44666. this._ambientTexture.dispose();
  44667. }
  44668. if (this._opacityTexture) {
  44669. this._opacityTexture.dispose();
  44670. }
  44671. if (this._reflectionTexture) {
  44672. this._reflectionTexture.dispose();
  44673. }
  44674. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44675. this._environmentBRDFTexture.dispose();
  44676. }
  44677. if (this._emissiveTexture) {
  44678. this._emissiveTexture.dispose();
  44679. }
  44680. if (this._metallicTexture) {
  44681. this._metallicTexture.dispose();
  44682. }
  44683. if (this._reflectivityTexture) {
  44684. this._reflectivityTexture.dispose();
  44685. }
  44686. if (this._bumpTexture) {
  44687. this._bumpTexture.dispose();
  44688. }
  44689. if (this._lightmapTexture) {
  44690. this._lightmapTexture.dispose();
  44691. }
  44692. if (this._refractionTexture) {
  44693. this._refractionTexture.dispose();
  44694. }
  44695. }
  44696. this._renderTargets.dispose();
  44697. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44698. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44699. }
  44700. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44701. };
  44702. /**
  44703. * Stores the reflectivity values based on metallic roughness workflow.
  44704. */
  44705. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44706. __decorate([
  44707. BABYLON.serializeAsImageProcessingConfiguration()
  44708. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44709. __decorate([
  44710. BABYLON.serialize()
  44711. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44712. __decorate([
  44713. BABYLON.serialize()
  44714. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44715. return PBRBaseMaterial;
  44716. }(BABYLON.PushMaterial));
  44717. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44718. })(BABYLON || (BABYLON = {}));
  44719. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44720. var BABYLON;
  44721. (function (BABYLON) {
  44722. /**
  44723. * The Physically based simple base material of BJS.
  44724. *
  44725. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44726. * It is used as the base class for both the specGloss and metalRough conventions.
  44727. */
  44728. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44729. __extends(PBRBaseSimpleMaterial, _super);
  44730. /**
  44731. * Instantiates a new PBRMaterial instance.
  44732. *
  44733. * @param name The material name
  44734. * @param scene The scene the material will be use in.
  44735. */
  44736. function PBRBaseSimpleMaterial(name, scene) {
  44737. var _this = _super.call(this, name, scene) || this;
  44738. /**
  44739. * Number of Simultaneous lights allowed on the material.
  44740. */
  44741. _this.maxSimultaneousLights = 4;
  44742. /**
  44743. * If sets to true, disables all the lights affecting the material.
  44744. */
  44745. _this.disableLighting = false;
  44746. /**
  44747. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44748. */
  44749. _this.invertNormalMapX = false;
  44750. /**
  44751. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44752. */
  44753. _this.invertNormalMapY = false;
  44754. /**
  44755. * Emissivie color used to self-illuminate the model.
  44756. */
  44757. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44758. /**
  44759. * Occlusion Channel Strenght.
  44760. */
  44761. _this.occlusionStrength = 1.0;
  44762. _this.useLightmapAsShadowmap = false;
  44763. _this._useAlphaFromAlbedoTexture = true;
  44764. _this._useAmbientInGrayScale = true;
  44765. return _this;
  44766. }
  44767. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44768. /**
  44769. * Gets the current double sided mode.
  44770. */
  44771. get: function () {
  44772. return this._twoSidedLighting;
  44773. },
  44774. /**
  44775. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44776. */
  44777. set: function (value) {
  44778. if (this._twoSidedLighting === value) {
  44779. return;
  44780. }
  44781. this._twoSidedLighting = value;
  44782. this.backFaceCulling = !value;
  44783. this._markAllSubMeshesAsTexturesDirty();
  44784. },
  44785. enumerable: true,
  44786. configurable: true
  44787. });
  44788. /**
  44789. * Return the active textures of the material.
  44790. */
  44791. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44792. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44793. if (this.environmentTexture) {
  44794. activeTextures.push(this.environmentTexture);
  44795. }
  44796. if (this.normalTexture) {
  44797. activeTextures.push(this.normalTexture);
  44798. }
  44799. if (this.emissiveTexture) {
  44800. activeTextures.push(this.emissiveTexture);
  44801. }
  44802. if (this.occlusionTexture) {
  44803. activeTextures.push(this.occlusionTexture);
  44804. }
  44805. if (this.lightmapTexture) {
  44806. activeTextures.push(this.lightmapTexture);
  44807. }
  44808. return activeTextures;
  44809. };
  44810. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44811. if (_super.prototype.hasTexture.call(this, texture)) {
  44812. return true;
  44813. }
  44814. if (this.lightmapTexture === texture) {
  44815. return true;
  44816. }
  44817. return false;
  44818. };
  44819. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44820. return "PBRBaseSimpleMaterial";
  44821. };
  44822. __decorate([
  44823. BABYLON.serialize(),
  44824. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44825. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44826. __decorate([
  44827. BABYLON.serialize(),
  44828. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44829. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44830. __decorate([
  44831. BABYLON.serializeAsTexture(),
  44832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44833. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44834. __decorate([
  44835. BABYLON.serialize(),
  44836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44837. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44838. __decorate([
  44839. BABYLON.serialize(),
  44840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44841. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44842. __decorate([
  44843. BABYLON.serializeAsTexture(),
  44844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44845. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44846. __decorate([
  44847. BABYLON.serializeAsColor3("emissive"),
  44848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44849. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44850. __decorate([
  44851. BABYLON.serializeAsTexture(),
  44852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44853. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44854. __decorate([
  44855. BABYLON.serialize(),
  44856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44857. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44858. __decorate([
  44859. BABYLON.serializeAsTexture(),
  44860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44861. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44862. __decorate([
  44863. BABYLON.serialize(),
  44864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44865. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44866. __decorate([
  44867. BABYLON.serialize()
  44868. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44869. __decorate([
  44870. BABYLON.serializeAsTexture(),
  44871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44872. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44873. __decorate([
  44874. BABYLON.serialize(),
  44875. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44876. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44877. return PBRBaseSimpleMaterial;
  44878. }(BABYLON.PBRBaseMaterial));
  44879. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44880. })(BABYLON || (BABYLON = {}));
  44881. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44882. var BABYLON;
  44883. (function (BABYLON) {
  44884. /**
  44885. * The Physically based material of BJS.
  44886. *
  44887. * This offers the main features of a standard PBR material.
  44888. * For more information, please refer to the documentation :
  44889. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44890. */
  44891. var PBRMaterial = /** @class */ (function (_super) {
  44892. __extends(PBRMaterial, _super);
  44893. /**
  44894. * Instantiates a new PBRMaterial instance.
  44895. *
  44896. * @param name The material name
  44897. * @param scene The scene the material will be use in.
  44898. */
  44899. function PBRMaterial(name, scene) {
  44900. var _this = _super.call(this, name, scene) || this;
  44901. /**
  44902. * Intensity of the direct lights e.g. the four lights available in your scene.
  44903. * This impacts both the direct diffuse and specular highlights.
  44904. */
  44905. _this.directIntensity = 1.0;
  44906. /**
  44907. * Intensity of the emissive part of the material.
  44908. * This helps controlling the emissive effect without modifying the emissive color.
  44909. */
  44910. _this.emissiveIntensity = 1.0;
  44911. /**
  44912. * Intensity of the environment e.g. how much the environment will light the object
  44913. * either through harmonics for rough material or through the refelction for shiny ones.
  44914. */
  44915. _this.environmentIntensity = 1.0;
  44916. /**
  44917. * This is a special control allowing the reduction of the specular highlights coming from the
  44918. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44919. */
  44920. _this.specularIntensity = 1.0;
  44921. /**
  44922. * Debug Control allowing disabling the bump map on this material.
  44923. */
  44924. _this.disableBumpMap = false;
  44925. /**
  44926. * AKA Occlusion Texture Intensity in other nomenclature.
  44927. */
  44928. _this.ambientTextureStrength = 1.0;
  44929. /**
  44930. * The color of a material in ambient lighting.
  44931. */
  44932. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44933. /**
  44934. * AKA Diffuse Color in other nomenclature.
  44935. */
  44936. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44937. /**
  44938. * AKA Specular Color in other nomenclature.
  44939. */
  44940. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44941. /**
  44942. * The color reflected from the material.
  44943. */
  44944. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44945. /**
  44946. * The color emitted from the material.
  44947. */
  44948. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44949. /**
  44950. * AKA Glossiness in other nomenclature.
  44951. */
  44952. _this.microSurface = 1.0;
  44953. /**
  44954. * source material index of refraction (IOR)' / 'destination material IOR.
  44955. */
  44956. _this.indexOfRefraction = 0.66;
  44957. /**
  44958. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44959. */
  44960. _this.invertRefractionY = false;
  44961. /**
  44962. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44963. * Materials half opaque for instance using refraction could benefit from this control.
  44964. */
  44965. _this.linkRefractionWithTransparency = false;
  44966. _this.useLightmapAsShadowmap = false;
  44967. /**
  44968. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44969. */
  44970. _this.useAlphaFromAlbedoTexture = false;
  44971. /**
  44972. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44973. */
  44974. _this.forceAlphaTest = false;
  44975. /**
  44976. * Defines the alpha limits in alpha test mode.
  44977. */
  44978. _this.alphaCutOff = 0.4;
  44979. /**
  44980. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44981. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44982. */
  44983. _this.useSpecularOverAlpha = true;
  44984. /**
  44985. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44986. */
  44987. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44988. /**
  44989. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44990. */
  44991. _this.useRoughnessFromMetallicTextureAlpha = true;
  44992. /**
  44993. * Specifies if the metallic texture contains the roughness information in its green channel.
  44994. */
  44995. _this.useRoughnessFromMetallicTextureGreen = false;
  44996. /**
  44997. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44998. */
  44999. _this.useMetallnessFromMetallicTextureBlue = false;
  45000. /**
  45001. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45002. */
  45003. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45004. /**
  45005. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45006. */
  45007. _this.useAmbientInGrayScale = false;
  45008. /**
  45009. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45010. * The material will try to infer what glossiness each pixel should be.
  45011. */
  45012. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45013. /**
  45014. * BJS is using an harcoded light falloff based on a manually sets up range.
  45015. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45016. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45017. */
  45018. _this.usePhysicalLightFalloff = true;
  45019. /**
  45020. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45021. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45022. */
  45023. _this.useRadianceOverAlpha = true;
  45024. /**
  45025. * Allows using an object space normal map (instead of tangent space).
  45026. */
  45027. _this.useObjectSpaceNormalMap = false;
  45028. /**
  45029. * Allows using the bump map in parallax mode.
  45030. */
  45031. _this.useParallax = false;
  45032. /**
  45033. * Allows using the bump map in parallax occlusion mode.
  45034. */
  45035. _this.useParallaxOcclusion = false;
  45036. /**
  45037. * Controls the scale bias of the parallax mode.
  45038. */
  45039. _this.parallaxScaleBias = 0.05;
  45040. /**
  45041. * If sets to true, disables all the lights affecting the material.
  45042. */
  45043. _this.disableLighting = false;
  45044. /**
  45045. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45046. */
  45047. _this.forceIrradianceInFragment = false;
  45048. /**
  45049. * Number of Simultaneous lights allowed on the material.
  45050. */
  45051. _this.maxSimultaneousLights = 4;
  45052. /**
  45053. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45054. */
  45055. _this.invertNormalMapX = false;
  45056. /**
  45057. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45058. */
  45059. _this.invertNormalMapY = false;
  45060. /**
  45061. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45062. */
  45063. _this.twoSidedLighting = false;
  45064. /**
  45065. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45066. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45067. */
  45068. _this.useAlphaFresnel = false;
  45069. /**
  45070. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45071. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45072. */
  45073. _this.useLinearAlphaFresnel = false;
  45074. /**
  45075. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45076. * And/Or occlude the blended part.
  45077. */
  45078. _this.environmentBRDFTexture = null;
  45079. /**
  45080. * Force normal to face away from face.
  45081. */
  45082. _this.forceNormalForward = false;
  45083. /**
  45084. * Enables specular anti aliasing in the PBR shader.
  45085. * It will both interacts on the Geometry for analytical and IBL lighting.
  45086. * It also prefilter the roughness map based on the bump values.
  45087. */
  45088. _this.enableSpecularAntiAliasing = false;
  45089. /**
  45090. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45091. * makes the reflect vector face the model (under horizon).
  45092. */
  45093. _this.useHorizonOcclusion = true;
  45094. /**
  45095. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45096. * too much the area relying on ambient texture to define their ambient occlusion.
  45097. */
  45098. _this.useRadianceOcclusion = true;
  45099. /**
  45100. * If set to true, no lighting calculations will be applied.
  45101. */
  45102. _this.unlit = false;
  45103. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45104. return _this;
  45105. }
  45106. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45107. /**
  45108. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45109. */
  45110. get: function () {
  45111. return this._PBRMATERIAL_OPAQUE;
  45112. },
  45113. enumerable: true,
  45114. configurable: true
  45115. });
  45116. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45117. /**
  45118. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45119. */
  45120. get: function () {
  45121. return this._PBRMATERIAL_ALPHATEST;
  45122. },
  45123. enumerable: true,
  45124. configurable: true
  45125. });
  45126. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45127. /**
  45128. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45129. */
  45130. get: function () {
  45131. return this._PBRMATERIAL_ALPHABLEND;
  45132. },
  45133. enumerable: true,
  45134. configurable: true
  45135. });
  45136. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45137. /**
  45138. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45139. * They are also discarded below the alpha cutoff threshold to improve performances.
  45140. */
  45141. get: function () {
  45142. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45143. },
  45144. enumerable: true,
  45145. configurable: true
  45146. });
  45147. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45148. /**
  45149. * Gets the image processing configuration used either in this material.
  45150. */
  45151. get: function () {
  45152. return this._imageProcessingConfiguration;
  45153. },
  45154. /**
  45155. * Sets the Default image processing configuration used either in the this material.
  45156. *
  45157. * If sets to null, the scene one is in use.
  45158. */
  45159. set: function (value) {
  45160. this._attachImageProcessingConfiguration(value);
  45161. // Ensure the effect will be rebuilt.
  45162. this._markAllSubMeshesAsTexturesDirty();
  45163. },
  45164. enumerable: true,
  45165. configurable: true
  45166. });
  45167. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45168. /**
  45169. * Gets wether the color curves effect is enabled.
  45170. */
  45171. get: function () {
  45172. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45173. },
  45174. /**
  45175. * Sets wether the color curves effect is enabled.
  45176. */
  45177. set: function (value) {
  45178. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45179. },
  45180. enumerable: true,
  45181. configurable: true
  45182. });
  45183. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45184. /**
  45185. * Gets wether the color grading effect is enabled.
  45186. */
  45187. get: function () {
  45188. return this.imageProcessingConfiguration.colorGradingEnabled;
  45189. },
  45190. /**
  45191. * Gets wether the color grading effect is enabled.
  45192. */
  45193. set: function (value) {
  45194. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45195. },
  45196. enumerable: true,
  45197. configurable: true
  45198. });
  45199. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45200. /**
  45201. * Gets wether tonemapping is enabled or not.
  45202. */
  45203. get: function () {
  45204. return this._imageProcessingConfiguration.toneMappingEnabled;
  45205. },
  45206. /**
  45207. * Sets wether tonemapping is enabled or not
  45208. */
  45209. set: function (value) {
  45210. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45211. },
  45212. enumerable: true,
  45213. configurable: true
  45214. });
  45215. ;
  45216. ;
  45217. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45218. /**
  45219. * The camera exposure used on this material.
  45220. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45221. * This corresponds to a photographic exposure.
  45222. */
  45223. get: function () {
  45224. return this._imageProcessingConfiguration.exposure;
  45225. },
  45226. /**
  45227. * The camera exposure used on this material.
  45228. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45229. * This corresponds to a photographic exposure.
  45230. */
  45231. set: function (value) {
  45232. this._imageProcessingConfiguration.exposure = value;
  45233. },
  45234. enumerable: true,
  45235. configurable: true
  45236. });
  45237. ;
  45238. ;
  45239. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45240. /**
  45241. * Gets The camera contrast used on this material.
  45242. */
  45243. get: function () {
  45244. return this._imageProcessingConfiguration.contrast;
  45245. },
  45246. /**
  45247. * Sets The camera contrast used on this material.
  45248. */
  45249. set: function (value) {
  45250. this._imageProcessingConfiguration.contrast = value;
  45251. },
  45252. enumerable: true,
  45253. configurable: true
  45254. });
  45255. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45256. /**
  45257. * Gets the Color Grading 2D Lookup Texture.
  45258. */
  45259. get: function () {
  45260. return this._imageProcessingConfiguration.colorGradingTexture;
  45261. },
  45262. /**
  45263. * Sets the Color Grading 2D Lookup Texture.
  45264. */
  45265. set: function (value) {
  45266. this._imageProcessingConfiguration.colorGradingTexture = value;
  45267. },
  45268. enumerable: true,
  45269. configurable: true
  45270. });
  45271. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45272. /**
  45273. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45274. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45275. * 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;
  45276. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45277. */
  45278. get: function () {
  45279. return this._imageProcessingConfiguration.colorCurves;
  45280. },
  45281. /**
  45282. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45283. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45284. * 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;
  45285. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45286. */
  45287. set: function (value) {
  45288. this._imageProcessingConfiguration.colorCurves = value;
  45289. },
  45290. enumerable: true,
  45291. configurable: true
  45292. });
  45293. /**
  45294. * Returns the name of this material class.
  45295. */
  45296. PBRMaterial.prototype.getClassName = function () {
  45297. return "PBRMaterial";
  45298. };
  45299. /**
  45300. * Returns an array of the actively used textures.
  45301. * @returns - Array of BaseTextures
  45302. */
  45303. PBRMaterial.prototype.getActiveTextures = function () {
  45304. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45305. if (this._albedoTexture) {
  45306. activeTextures.push(this._albedoTexture);
  45307. }
  45308. if (this._ambientTexture) {
  45309. activeTextures.push(this._ambientTexture);
  45310. }
  45311. if (this._opacityTexture) {
  45312. activeTextures.push(this._opacityTexture);
  45313. }
  45314. if (this._reflectionTexture) {
  45315. activeTextures.push(this._reflectionTexture);
  45316. }
  45317. if (this._emissiveTexture) {
  45318. activeTextures.push(this._emissiveTexture);
  45319. }
  45320. if (this._reflectivityTexture) {
  45321. activeTextures.push(this._reflectivityTexture);
  45322. }
  45323. if (this._metallicTexture) {
  45324. activeTextures.push(this._metallicTexture);
  45325. }
  45326. if (this._microSurfaceTexture) {
  45327. activeTextures.push(this._microSurfaceTexture);
  45328. }
  45329. if (this._bumpTexture) {
  45330. activeTextures.push(this._bumpTexture);
  45331. }
  45332. if (this._lightmapTexture) {
  45333. activeTextures.push(this._lightmapTexture);
  45334. }
  45335. if (this._refractionTexture) {
  45336. activeTextures.push(this._refractionTexture);
  45337. }
  45338. return activeTextures;
  45339. };
  45340. /**
  45341. * Checks to see if a texture is used in the material.
  45342. * @param texture - Base texture to use.
  45343. * @returns - Boolean specifying if a texture is used in the material.
  45344. */
  45345. PBRMaterial.prototype.hasTexture = function (texture) {
  45346. if (_super.prototype.hasTexture.call(this, texture)) {
  45347. return true;
  45348. }
  45349. if (this._albedoTexture === texture) {
  45350. return true;
  45351. }
  45352. if (this._ambientTexture === texture) {
  45353. return true;
  45354. }
  45355. if (this._opacityTexture === texture) {
  45356. return true;
  45357. }
  45358. if (this._reflectionTexture === texture) {
  45359. return true;
  45360. }
  45361. if (this._reflectivityTexture === texture) {
  45362. return true;
  45363. }
  45364. if (this._metallicTexture === texture) {
  45365. return true;
  45366. }
  45367. if (this._microSurfaceTexture === texture) {
  45368. return true;
  45369. }
  45370. if (this._bumpTexture === texture) {
  45371. return true;
  45372. }
  45373. if (this._lightmapTexture === texture) {
  45374. return true;
  45375. }
  45376. if (this._refractionTexture === texture) {
  45377. return true;
  45378. }
  45379. return false;
  45380. };
  45381. /**
  45382. * Makes a duplicate of the current material.
  45383. * @param name - name to use for the new material.
  45384. */
  45385. PBRMaterial.prototype.clone = function (name) {
  45386. var _this = this;
  45387. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45388. clone.id = name;
  45389. clone.name = name;
  45390. return clone;
  45391. };
  45392. /**
  45393. * Serializes this PBR Material.
  45394. * @returns - An object with the serialized material.
  45395. */
  45396. PBRMaterial.prototype.serialize = function () {
  45397. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45398. serializationObject.customType = "BABYLON.PBRMaterial";
  45399. return serializationObject;
  45400. };
  45401. // Statics
  45402. /**
  45403. * Parses a PBR Material from a serialized object.
  45404. * @param source - Serialized object.
  45405. * @param scene - BJS scene instance.
  45406. * @param rootUrl - url for the scene object
  45407. * @returns - PBRMaterial
  45408. */
  45409. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45410. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45411. };
  45412. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45413. /**
  45414. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45415. */
  45416. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45417. /**
  45418. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45419. */
  45420. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45421. /**
  45422. * 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.
  45423. * They are also discarded below the alpha cutoff threshold to improve performances.
  45424. */
  45425. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45426. __decorate([
  45427. BABYLON.serialize(),
  45428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45429. ], PBRMaterial.prototype, "directIntensity", void 0);
  45430. __decorate([
  45431. BABYLON.serialize(),
  45432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45433. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45434. __decorate([
  45435. BABYLON.serialize(),
  45436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45437. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45438. __decorate([
  45439. BABYLON.serialize(),
  45440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45441. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45442. __decorate([
  45443. BABYLON.serialize(),
  45444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45445. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45446. __decorate([
  45447. BABYLON.serializeAsTexture(),
  45448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45449. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45450. __decorate([
  45451. BABYLON.serializeAsTexture(),
  45452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45453. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45454. __decorate([
  45455. BABYLON.serialize(),
  45456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45457. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45458. __decorate([
  45459. BABYLON.serializeAsTexture(),
  45460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45461. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45462. __decorate([
  45463. BABYLON.serializeAsTexture(),
  45464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45465. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45466. __decorate([
  45467. BABYLON.serializeAsTexture(),
  45468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45469. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45470. __decorate([
  45471. BABYLON.serializeAsTexture(),
  45472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45473. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45474. __decorate([
  45475. BABYLON.serializeAsTexture(),
  45476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45477. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45478. __decorate([
  45479. BABYLON.serialize(),
  45480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45481. ], PBRMaterial.prototype, "metallic", void 0);
  45482. __decorate([
  45483. BABYLON.serialize(),
  45484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45485. ], PBRMaterial.prototype, "roughness", void 0);
  45486. __decorate([
  45487. BABYLON.serializeAsTexture(),
  45488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45489. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45490. __decorate([
  45491. BABYLON.serializeAsTexture(),
  45492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45493. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45494. __decorate([
  45495. BABYLON.serializeAsTexture(),
  45496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45497. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45498. __decorate([
  45499. BABYLON.serializeAsTexture(),
  45500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45501. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45502. __decorate([
  45503. BABYLON.serializeAsColor3("ambient"),
  45504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45505. ], PBRMaterial.prototype, "ambientColor", void 0);
  45506. __decorate([
  45507. BABYLON.serializeAsColor3("albedo"),
  45508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45509. ], PBRMaterial.prototype, "albedoColor", void 0);
  45510. __decorate([
  45511. BABYLON.serializeAsColor3("reflectivity"),
  45512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45513. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45514. __decorate([
  45515. BABYLON.serializeAsColor3("reflection"),
  45516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45517. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45518. __decorate([
  45519. BABYLON.serializeAsColor3("emissive"),
  45520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45521. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45522. __decorate([
  45523. BABYLON.serialize(),
  45524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45525. ], PBRMaterial.prototype, "microSurface", void 0);
  45526. __decorate([
  45527. BABYLON.serialize(),
  45528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45529. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45530. __decorate([
  45531. BABYLON.serialize(),
  45532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45533. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45534. __decorate([
  45535. BABYLON.serialize(),
  45536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45537. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45538. __decorate([
  45539. BABYLON.serialize(),
  45540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45541. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45542. __decorate([
  45543. BABYLON.serialize(),
  45544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45545. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45546. __decorate([
  45547. BABYLON.serialize(),
  45548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45549. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45550. __decorate([
  45551. BABYLON.serialize(),
  45552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45553. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45554. __decorate([
  45555. BABYLON.serialize(),
  45556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45557. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45558. __decorate([
  45559. BABYLON.serialize(),
  45560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45561. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45562. __decorate([
  45563. BABYLON.serialize(),
  45564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45565. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45566. __decorate([
  45567. BABYLON.serialize(),
  45568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45569. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45570. __decorate([
  45571. BABYLON.serialize(),
  45572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45573. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45574. __decorate([
  45575. BABYLON.serialize(),
  45576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45577. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45578. __decorate([
  45579. BABYLON.serialize(),
  45580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45581. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45582. __decorate([
  45583. BABYLON.serialize(),
  45584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45585. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45586. __decorate([
  45587. BABYLON.serialize(),
  45588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45589. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45590. __decorate([
  45591. BABYLON.serialize(),
  45592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45593. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45594. __decorate([
  45595. BABYLON.serialize(),
  45596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45597. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45598. __decorate([
  45599. BABYLON.serialize(),
  45600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45601. ], PBRMaterial.prototype, "useParallax", void 0);
  45602. __decorate([
  45603. BABYLON.serialize(),
  45604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45605. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45606. __decorate([
  45607. BABYLON.serialize(),
  45608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45609. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45610. __decorate([
  45611. BABYLON.serialize(),
  45612. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45613. ], PBRMaterial.prototype, "disableLighting", void 0);
  45614. __decorate([
  45615. BABYLON.serialize(),
  45616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45617. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45618. __decorate([
  45619. BABYLON.serialize(),
  45620. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45621. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45622. __decorate([
  45623. BABYLON.serialize(),
  45624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45625. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45626. __decorate([
  45627. BABYLON.serialize(),
  45628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45629. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45630. __decorate([
  45631. BABYLON.serialize(),
  45632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45633. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45634. __decorate([
  45635. BABYLON.serialize(),
  45636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45637. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45638. __decorate([
  45639. BABYLON.serialize(),
  45640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45641. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45642. __decorate([
  45643. BABYLON.serializeAsTexture(),
  45644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45645. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45646. __decorate([
  45647. BABYLON.serialize(),
  45648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45649. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45650. __decorate([
  45651. BABYLON.serialize(),
  45652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45653. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45654. __decorate([
  45655. BABYLON.serialize(),
  45656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45657. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45658. __decorate([
  45659. BABYLON.serialize(),
  45660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45661. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45662. __decorate([
  45663. BABYLON.serialize(),
  45664. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45665. ], PBRMaterial.prototype, "unlit", void 0);
  45666. return PBRMaterial;
  45667. }(BABYLON.PBRBaseMaterial));
  45668. BABYLON.PBRMaterial = PBRMaterial;
  45669. })(BABYLON || (BABYLON = {}));
  45670. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45671. var BABYLON;
  45672. (function (BABYLON) {
  45673. /**
  45674. * The PBR material of BJS following the metal roughness convention.
  45675. *
  45676. * This fits to the PBR convention in the GLTF definition:
  45677. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45678. */
  45679. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45680. __extends(PBRMetallicRoughnessMaterial, _super);
  45681. /**
  45682. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45683. *
  45684. * @param name The material name
  45685. * @param scene The scene the material will be use in.
  45686. */
  45687. function PBRMetallicRoughnessMaterial(name, scene) {
  45688. var _this = _super.call(this, name, scene) || this;
  45689. _this._useRoughnessFromMetallicTextureAlpha = false;
  45690. _this._useRoughnessFromMetallicTextureGreen = true;
  45691. _this._useMetallnessFromMetallicTextureBlue = true;
  45692. _this.metallic = 1.0;
  45693. _this.roughness = 1.0;
  45694. return _this;
  45695. }
  45696. /**
  45697. * Return the currrent class name of the material.
  45698. */
  45699. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45700. return "PBRMetallicRoughnessMaterial";
  45701. };
  45702. /**
  45703. * Return the active textures of the material.
  45704. */
  45705. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45706. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45707. if (this.baseTexture) {
  45708. activeTextures.push(this.baseTexture);
  45709. }
  45710. if (this.metallicRoughnessTexture) {
  45711. activeTextures.push(this.metallicRoughnessTexture);
  45712. }
  45713. return activeTextures;
  45714. };
  45715. /**
  45716. * Checks to see if a texture is used in the material.
  45717. * @param texture - Base texture to use.
  45718. * @returns - Boolean specifying if a texture is used in the material.
  45719. */
  45720. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45721. if (_super.prototype.hasTexture.call(this, texture)) {
  45722. return true;
  45723. }
  45724. if (this.baseTexture === texture) {
  45725. return true;
  45726. }
  45727. if (this.metallicRoughnessTexture === texture) {
  45728. return true;
  45729. }
  45730. return false;
  45731. };
  45732. /**
  45733. * Makes a duplicate of the current material.
  45734. * @param name - name to use for the new material.
  45735. */
  45736. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45737. var _this = this;
  45738. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45739. clone.id = name;
  45740. clone.name = name;
  45741. return clone;
  45742. };
  45743. /**
  45744. * Serialize the material to a parsable JSON object.
  45745. */
  45746. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45747. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45748. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45749. return serializationObject;
  45750. };
  45751. /**
  45752. * Parses a JSON object correponding to the serialize function.
  45753. */
  45754. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45755. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45756. };
  45757. __decorate([
  45758. BABYLON.serializeAsColor3(),
  45759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45760. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45761. __decorate([
  45762. BABYLON.serializeAsTexture(),
  45763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45764. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45765. __decorate([
  45766. BABYLON.serialize(),
  45767. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45768. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45769. __decorate([
  45770. BABYLON.serialize(),
  45771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45772. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45773. __decorate([
  45774. BABYLON.serializeAsTexture(),
  45775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45776. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45777. return PBRMetallicRoughnessMaterial;
  45778. }(BABYLON.PBRBaseSimpleMaterial));
  45779. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45780. })(BABYLON || (BABYLON = {}));
  45781. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45782. var BABYLON;
  45783. (function (BABYLON) {
  45784. /**
  45785. * The PBR material of BJS following the specular glossiness convention.
  45786. *
  45787. * This fits to the PBR convention in the GLTF definition:
  45788. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45789. */
  45790. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45791. __extends(PBRSpecularGlossinessMaterial, _super);
  45792. /**
  45793. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45794. *
  45795. * @param name The material name
  45796. * @param scene The scene the material will be use in.
  45797. */
  45798. function PBRSpecularGlossinessMaterial(name, scene) {
  45799. var _this = _super.call(this, name, scene) || this;
  45800. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45801. return _this;
  45802. }
  45803. /**
  45804. * Return the currrent class name of the material.
  45805. */
  45806. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45807. return "PBRSpecularGlossinessMaterial";
  45808. };
  45809. /**
  45810. * Return the active textures of the material.
  45811. */
  45812. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45813. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45814. if (this.diffuseTexture) {
  45815. activeTextures.push(this.diffuseTexture);
  45816. }
  45817. if (this.specularGlossinessTexture) {
  45818. activeTextures.push(this.specularGlossinessTexture);
  45819. }
  45820. return activeTextures;
  45821. };
  45822. /**
  45823. * Checks to see if a texture is used in the material.
  45824. * @param texture - Base texture to use.
  45825. * @returns - Boolean specifying if a texture is used in the material.
  45826. */
  45827. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45828. if (_super.prototype.hasTexture.call(this, texture)) {
  45829. return true;
  45830. }
  45831. if (this.diffuseTexture === texture) {
  45832. return true;
  45833. }
  45834. if (this.specularGlossinessTexture === texture) {
  45835. return true;
  45836. }
  45837. return false;
  45838. };
  45839. /**
  45840. * Makes a duplicate of the current material.
  45841. * @param name - name to use for the new material.
  45842. */
  45843. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45844. var _this = this;
  45845. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45846. clone.id = name;
  45847. clone.name = name;
  45848. return clone;
  45849. };
  45850. /**
  45851. * Serialize the material to a parsable JSON object.
  45852. */
  45853. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45854. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45855. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45856. return serializationObject;
  45857. };
  45858. /**
  45859. * Parses a JSON object correponding to the serialize function.
  45860. */
  45861. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45862. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45863. };
  45864. __decorate([
  45865. BABYLON.serializeAsColor3("diffuse"),
  45866. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45867. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45868. __decorate([
  45869. BABYLON.serializeAsTexture(),
  45870. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45871. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45872. __decorate([
  45873. BABYLON.serializeAsColor3("specular"),
  45874. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45875. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45876. __decorate([
  45877. BABYLON.serialize(),
  45878. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45879. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45880. __decorate([
  45881. BABYLON.serializeAsTexture(),
  45882. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45883. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45884. return PBRSpecularGlossinessMaterial;
  45885. }(BABYLON.PBRBaseSimpleMaterial));
  45886. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45887. })(BABYLON || (BABYLON = {}));
  45888. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45889. var BABYLON;
  45890. (function (BABYLON) {
  45891. BABYLON.CameraInputTypes = {};
  45892. var CameraInputsManager = /** @class */ (function () {
  45893. function CameraInputsManager(camera) {
  45894. this.attached = {};
  45895. this.camera = camera;
  45896. this.checkInputs = function () { };
  45897. }
  45898. /**
  45899. * Add an input method to a camera.
  45900. * builtin inputs example: camera.inputs.addGamepad();
  45901. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  45902. * @param input camera input method
  45903. */
  45904. CameraInputsManager.prototype.add = function (input) {
  45905. var type = input.getSimpleName();
  45906. if (this.attached[type]) {
  45907. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45908. return;
  45909. }
  45910. this.attached[type] = input;
  45911. input.camera = this.camera;
  45912. //for checkInputs, we are dynamically creating a function
  45913. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45914. if (input.checkInputs) {
  45915. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45916. }
  45917. if (this.attachedElement) {
  45918. input.attachControl(this.attachedElement);
  45919. }
  45920. };
  45921. /**
  45922. * Remove a specific input method from a camera
  45923. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45924. * @param inputToRemove camera input method
  45925. */
  45926. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45927. for (var cam in this.attached) {
  45928. var input = this.attached[cam];
  45929. if (input === inputToRemove) {
  45930. input.detachControl(this.attachedElement);
  45931. input.camera = null;
  45932. delete this.attached[cam];
  45933. this.rebuildInputCheck();
  45934. }
  45935. }
  45936. };
  45937. CameraInputsManager.prototype.removeByType = function (inputType) {
  45938. for (var cam in this.attached) {
  45939. var input = this.attached[cam];
  45940. if (input.getClassName() === inputType) {
  45941. input.detachControl(this.attachedElement);
  45942. input.camera = null;
  45943. delete this.attached[cam];
  45944. this.rebuildInputCheck();
  45945. }
  45946. }
  45947. };
  45948. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45949. var current = this.checkInputs;
  45950. return function () {
  45951. current();
  45952. fn();
  45953. };
  45954. };
  45955. CameraInputsManager.prototype.attachInput = function (input) {
  45956. if (this.attachedElement) {
  45957. input.attachControl(this.attachedElement, this.noPreventDefault);
  45958. }
  45959. };
  45960. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45961. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45962. if (this.attachedElement) {
  45963. return;
  45964. }
  45965. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45966. this.attachedElement = element;
  45967. this.noPreventDefault = noPreventDefault;
  45968. for (var cam in this.attached) {
  45969. this.attached[cam].attachControl(element, noPreventDefault);
  45970. }
  45971. };
  45972. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45973. if (disconnect === void 0) { disconnect = false; }
  45974. if (this.attachedElement !== element) {
  45975. return;
  45976. }
  45977. for (var cam in this.attached) {
  45978. this.attached[cam].detachControl(element);
  45979. if (disconnect) {
  45980. this.attached[cam].camera = null;
  45981. }
  45982. }
  45983. this.attachedElement = null;
  45984. };
  45985. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45986. this.checkInputs = function () { };
  45987. for (var cam in this.attached) {
  45988. var input = this.attached[cam];
  45989. if (input.checkInputs) {
  45990. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45991. }
  45992. }
  45993. };
  45994. /**
  45995. * Remove all attached input methods from a camera
  45996. */
  45997. CameraInputsManager.prototype.clear = function () {
  45998. if (this.attachedElement) {
  45999. this.detachElement(this.attachedElement, true);
  46000. }
  46001. this.attached = {};
  46002. this.attachedElement = null;
  46003. this.checkInputs = function () { };
  46004. };
  46005. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46006. var inputs = {};
  46007. for (var cam in this.attached) {
  46008. var input = this.attached[cam];
  46009. var res = BABYLON.SerializationHelper.Serialize(input);
  46010. inputs[input.getClassName()] = res;
  46011. }
  46012. serializedCamera.inputsmgr = inputs;
  46013. };
  46014. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46015. var parsedInputs = parsedCamera.inputsmgr;
  46016. if (parsedInputs) {
  46017. this.clear();
  46018. for (var n in parsedInputs) {
  46019. var construct = BABYLON.CameraInputTypes[n];
  46020. if (construct) {
  46021. var parsedinput = parsedInputs[n];
  46022. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46023. this.add(input);
  46024. }
  46025. }
  46026. }
  46027. else {
  46028. //2016-03-08 this part is for managing backward compatibility
  46029. for (var n in this.attached) {
  46030. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46031. if (construct) {
  46032. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46033. this.remove(this.attached[n]);
  46034. this.add(input);
  46035. }
  46036. }
  46037. }
  46038. };
  46039. return CameraInputsManager;
  46040. }());
  46041. BABYLON.CameraInputsManager = CameraInputsManager;
  46042. })(BABYLON || (BABYLON = {}));
  46043. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46044. var BABYLON;
  46045. (function (BABYLON) {
  46046. var TargetCamera = /** @class */ (function (_super) {
  46047. __extends(TargetCamera, _super);
  46048. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46049. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46050. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46051. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46052. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46053. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46054. _this.speed = 2.0;
  46055. _this.noRotationConstraint = false;
  46056. _this.lockedTarget = null;
  46057. _this._currentTarget = BABYLON.Vector3.Zero();
  46058. _this._viewMatrix = BABYLON.Matrix.Zero();
  46059. _this._camMatrix = BABYLON.Matrix.Zero();
  46060. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46061. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46062. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46063. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46064. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46065. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46066. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46067. return _this;
  46068. }
  46069. TargetCamera.prototype.getFrontPosition = function (distance) {
  46070. this.getWorldMatrix();
  46071. var direction = this.getTarget().subtract(this.position);
  46072. direction.normalize();
  46073. direction.scaleInPlace(distance);
  46074. return this.globalPosition.add(direction);
  46075. };
  46076. TargetCamera.prototype._getLockedTargetPosition = function () {
  46077. if (!this.lockedTarget) {
  46078. return null;
  46079. }
  46080. if (this.lockedTarget.absolutePosition) {
  46081. this.lockedTarget.computeWorldMatrix();
  46082. }
  46083. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46084. };
  46085. TargetCamera.prototype.storeState = function () {
  46086. this._storedPosition = this.position.clone();
  46087. this._storedRotation = this.rotation.clone();
  46088. if (this.rotationQuaternion) {
  46089. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46090. }
  46091. return _super.prototype.storeState.call(this);
  46092. };
  46093. /**
  46094. * Restored camera state. You must call storeState() first
  46095. */
  46096. TargetCamera.prototype._restoreStateValues = function () {
  46097. if (!_super.prototype._restoreStateValues.call(this)) {
  46098. return false;
  46099. }
  46100. this.position = this._storedPosition.clone();
  46101. this.rotation = this._storedRotation.clone();
  46102. if (this.rotationQuaternion) {
  46103. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46104. }
  46105. this.cameraDirection.copyFromFloats(0, 0, 0);
  46106. this.cameraRotation.copyFromFloats(0, 0);
  46107. return true;
  46108. };
  46109. // Cache
  46110. TargetCamera.prototype._initCache = function () {
  46111. _super.prototype._initCache.call(this);
  46112. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46113. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46114. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46115. };
  46116. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46117. if (!ignoreParentClass) {
  46118. _super.prototype._updateCache.call(this);
  46119. }
  46120. var lockedTargetPosition = this._getLockedTargetPosition();
  46121. if (!lockedTargetPosition) {
  46122. this._cache.lockedTarget = null;
  46123. }
  46124. else {
  46125. if (!this._cache.lockedTarget) {
  46126. this._cache.lockedTarget = lockedTargetPosition.clone();
  46127. }
  46128. else {
  46129. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46130. }
  46131. }
  46132. this._cache.rotation.copyFrom(this.rotation);
  46133. if (this.rotationQuaternion)
  46134. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46135. };
  46136. // Synchronized
  46137. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46138. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46139. return false;
  46140. }
  46141. var lockedTargetPosition = this._getLockedTargetPosition();
  46142. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46143. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46144. };
  46145. // Methods
  46146. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46147. var engine = this.getEngine();
  46148. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46149. };
  46150. // Target
  46151. TargetCamera.prototype.setTarget = function (target) {
  46152. this.upVector.normalize();
  46153. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46154. this._camMatrix.invert();
  46155. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46156. var vDir = target.subtract(this.position);
  46157. if (vDir.x >= 0.0) {
  46158. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46159. }
  46160. else {
  46161. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46162. }
  46163. this.rotation.z = 0;
  46164. if (isNaN(this.rotation.x)) {
  46165. this.rotation.x = 0;
  46166. }
  46167. if (isNaN(this.rotation.y)) {
  46168. this.rotation.y = 0;
  46169. }
  46170. if (isNaN(this.rotation.z)) {
  46171. this.rotation.z = 0;
  46172. }
  46173. if (this.rotationQuaternion) {
  46174. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46175. }
  46176. };
  46177. /**
  46178. * Return the current target position of the camera. This value is expressed in local space.
  46179. */
  46180. TargetCamera.prototype.getTarget = function () {
  46181. return this._currentTarget;
  46182. };
  46183. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46184. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46185. };
  46186. TargetCamera.prototype._updatePosition = function () {
  46187. if (this.parent) {
  46188. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46189. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46190. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46191. return;
  46192. }
  46193. this.position.addInPlace(this.cameraDirection);
  46194. };
  46195. TargetCamera.prototype._checkInputs = function () {
  46196. var needToMove = this._decideIfNeedsToMove();
  46197. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46198. // Move
  46199. if (needToMove) {
  46200. this._updatePosition();
  46201. }
  46202. // Rotate
  46203. if (needToRotate) {
  46204. this.rotation.x += this.cameraRotation.x;
  46205. this.rotation.y += this.cameraRotation.y;
  46206. //rotate, if quaternion is set and rotation was used
  46207. if (this.rotationQuaternion) {
  46208. var len = this.rotation.lengthSquared();
  46209. if (len) {
  46210. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46211. }
  46212. }
  46213. if (!this.noRotationConstraint) {
  46214. var limit = (Math.PI / 2) * 0.95;
  46215. if (this.rotation.x > limit)
  46216. this.rotation.x = limit;
  46217. if (this.rotation.x < -limit)
  46218. this.rotation.x = -limit;
  46219. }
  46220. }
  46221. // Inertia
  46222. if (needToMove) {
  46223. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46224. this.cameraDirection.x = 0;
  46225. }
  46226. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46227. this.cameraDirection.y = 0;
  46228. }
  46229. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46230. this.cameraDirection.z = 0;
  46231. }
  46232. this.cameraDirection.scaleInPlace(this.inertia);
  46233. }
  46234. if (needToRotate) {
  46235. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46236. this.cameraRotation.x = 0;
  46237. }
  46238. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46239. this.cameraRotation.y = 0;
  46240. }
  46241. this.cameraRotation.scaleInPlace(this.inertia);
  46242. }
  46243. _super.prototype._checkInputs.call(this);
  46244. };
  46245. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46246. if (this.rotationQuaternion) {
  46247. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46248. }
  46249. else {
  46250. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46251. }
  46252. //update the up vector!
  46253. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46254. };
  46255. TargetCamera.prototype._getViewMatrix = function () {
  46256. if (this.lockedTarget) {
  46257. this.setTarget(this._getLockedTargetPosition());
  46258. }
  46259. // Compute
  46260. this._updateCameraRotationMatrix();
  46261. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46262. // Computing target and final matrix
  46263. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46264. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46265. return this._viewMatrix;
  46266. };
  46267. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46268. if (this.parent) {
  46269. var parentWorldMatrix = this.parent.getWorldMatrix();
  46270. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46271. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46272. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46273. this._markSyncedWithParent();
  46274. }
  46275. else {
  46276. this._globalPosition.copyFrom(this.position);
  46277. this._globalCurrentTarget.copyFrom(target);
  46278. this._globalCurrentUpVector.copyFrom(up);
  46279. }
  46280. if (this.getScene().useRightHandedSystem) {
  46281. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46282. }
  46283. else {
  46284. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46285. }
  46286. };
  46287. /**
  46288. * @override
  46289. * Override Camera.createRigCamera
  46290. */
  46291. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46292. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46293. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46294. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46295. if (!this.rotationQuaternion) {
  46296. this.rotationQuaternion = new BABYLON.Quaternion();
  46297. }
  46298. rigCamera._cameraRigParams = {};
  46299. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46300. }
  46301. return rigCamera;
  46302. }
  46303. return null;
  46304. };
  46305. /**
  46306. * @override
  46307. * Override Camera._updateRigCameras
  46308. */
  46309. TargetCamera.prototype._updateRigCameras = function () {
  46310. var camLeft = this._rigCameras[0];
  46311. var camRight = this._rigCameras[1];
  46312. switch (this.cameraRigMode) {
  46313. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46314. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46315. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46316. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46317. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46318. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46319. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46320. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46321. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46322. camLeft.setTarget(this.getTarget());
  46323. camRight.setTarget(this.getTarget());
  46324. break;
  46325. case BABYLON.Camera.RIG_MODE_VR:
  46326. if (camLeft.rotationQuaternion) {
  46327. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46328. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46329. }
  46330. else {
  46331. camLeft.rotation.copyFrom(this.rotation);
  46332. camRight.rotation.copyFrom(this.rotation);
  46333. }
  46334. camLeft.position.copyFrom(this.position);
  46335. camRight.position.copyFrom(this.position);
  46336. break;
  46337. }
  46338. _super.prototype._updateRigCameras.call(this);
  46339. };
  46340. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46341. if (!this._rigCamTransformMatrix) {
  46342. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46343. }
  46344. var target = this.getTarget();
  46345. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46346. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46347. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46348. };
  46349. TargetCamera.prototype.getClassName = function () {
  46350. return "TargetCamera";
  46351. };
  46352. __decorate([
  46353. BABYLON.serializeAsVector3()
  46354. ], TargetCamera.prototype, "rotation", void 0);
  46355. __decorate([
  46356. BABYLON.serialize()
  46357. ], TargetCamera.prototype, "speed", void 0);
  46358. __decorate([
  46359. BABYLON.serializeAsMeshReference("lockedTargetId")
  46360. ], TargetCamera.prototype, "lockedTarget", void 0);
  46361. return TargetCamera;
  46362. }(BABYLON.Camera));
  46363. BABYLON.TargetCamera = TargetCamera;
  46364. })(BABYLON || (BABYLON = {}));
  46365. //# sourceMappingURL=babylon.targetCamera.js.map
  46366. var BABYLON;
  46367. (function (BABYLON) {
  46368. var FreeCameraMouseInput = /** @class */ (function () {
  46369. function FreeCameraMouseInput(touchEnabled) {
  46370. if (touchEnabled === void 0) { touchEnabled = true; }
  46371. this.touchEnabled = touchEnabled;
  46372. this.buttons = [0, 1, 2];
  46373. this.angularSensibility = 2000.0;
  46374. this.previousPosition = null;
  46375. }
  46376. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46377. var _this = this;
  46378. var engine = this.camera.getEngine();
  46379. if (!this._pointerInput) {
  46380. this._pointerInput = function (p, s) {
  46381. var evt = p.event;
  46382. if (engine.isInVRExclusivePointerMode) {
  46383. return;
  46384. }
  46385. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46386. return;
  46387. }
  46388. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46389. return;
  46390. }
  46391. var srcElement = (evt.srcElement || evt.target);
  46392. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46393. try {
  46394. srcElement.setPointerCapture(evt.pointerId);
  46395. }
  46396. catch (e) {
  46397. //Nothing to do with the error. Execution will continue.
  46398. }
  46399. _this.previousPosition = {
  46400. x: evt.clientX,
  46401. y: evt.clientY
  46402. };
  46403. if (!noPreventDefault) {
  46404. evt.preventDefault();
  46405. element.focus();
  46406. }
  46407. }
  46408. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46409. try {
  46410. srcElement.releasePointerCapture(evt.pointerId);
  46411. }
  46412. catch (e) {
  46413. //Nothing to do with the error.
  46414. }
  46415. _this.previousPosition = null;
  46416. if (!noPreventDefault) {
  46417. evt.preventDefault();
  46418. }
  46419. }
  46420. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46421. if (!_this.previousPosition || engine.isPointerLock) {
  46422. return;
  46423. }
  46424. var offsetX = evt.clientX - _this.previousPosition.x;
  46425. if (_this.camera.getScene().useRightHandedSystem)
  46426. offsetX *= -1;
  46427. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46428. offsetX *= -1;
  46429. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46430. var offsetY = evt.clientY - _this.previousPosition.y;
  46431. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46432. _this.previousPosition = {
  46433. x: evt.clientX,
  46434. y: evt.clientY
  46435. };
  46436. if (!noPreventDefault) {
  46437. evt.preventDefault();
  46438. }
  46439. }
  46440. };
  46441. }
  46442. this._onMouseMove = function (evt) {
  46443. if (!engine.isPointerLock) {
  46444. return;
  46445. }
  46446. if (engine.isInVRExclusivePointerMode) {
  46447. return;
  46448. }
  46449. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46450. if (_this.camera.getScene().useRightHandedSystem)
  46451. offsetX *= -1;
  46452. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46453. offsetX *= -1;
  46454. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46455. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46456. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46457. _this.previousPosition = null;
  46458. if (!noPreventDefault) {
  46459. evt.preventDefault();
  46460. }
  46461. };
  46462. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46463. element.addEventListener("mousemove", this._onMouseMove, false);
  46464. };
  46465. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46466. if (this._observer && element) {
  46467. this.camera.getScene().onPointerObservable.remove(this._observer);
  46468. if (this._onMouseMove) {
  46469. element.removeEventListener("mousemove", this._onMouseMove);
  46470. }
  46471. this._observer = null;
  46472. this._onMouseMove = null;
  46473. this.previousPosition = null;
  46474. }
  46475. };
  46476. FreeCameraMouseInput.prototype.getClassName = function () {
  46477. return "FreeCameraMouseInput";
  46478. };
  46479. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46480. return "mouse";
  46481. };
  46482. __decorate([
  46483. BABYLON.serialize()
  46484. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46485. __decorate([
  46486. BABYLON.serialize()
  46487. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46488. return FreeCameraMouseInput;
  46489. }());
  46490. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46491. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46492. })(BABYLON || (BABYLON = {}));
  46493. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46494. var BABYLON;
  46495. (function (BABYLON) {
  46496. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46497. function FreeCameraKeyboardMoveInput() {
  46498. this._keys = new Array();
  46499. this.keysUp = [38];
  46500. this.keysDown = [40];
  46501. this.keysLeft = [37];
  46502. this.keysRight = [39];
  46503. }
  46504. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46505. var _this = this;
  46506. if (this._onCanvasBlurObserver) {
  46507. return;
  46508. }
  46509. this._scene = this.camera.getScene();
  46510. this._engine = this._scene.getEngine();
  46511. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46512. _this._keys = [];
  46513. });
  46514. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46515. var evt = info.event;
  46516. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46517. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46518. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46519. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46520. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46521. var index = _this._keys.indexOf(evt.keyCode);
  46522. if (index === -1) {
  46523. _this._keys.push(evt.keyCode);
  46524. }
  46525. if (!noPreventDefault) {
  46526. evt.preventDefault();
  46527. }
  46528. }
  46529. }
  46530. else {
  46531. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46532. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46533. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46534. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46535. var index = _this._keys.indexOf(evt.keyCode);
  46536. if (index >= 0) {
  46537. _this._keys.splice(index, 1);
  46538. }
  46539. if (!noPreventDefault) {
  46540. evt.preventDefault();
  46541. }
  46542. }
  46543. }
  46544. });
  46545. };
  46546. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46547. if (this._scene) {
  46548. if (this._onKeyboardObserver) {
  46549. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46550. }
  46551. if (this._onCanvasBlurObserver) {
  46552. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46553. }
  46554. this._onKeyboardObserver = null;
  46555. this._onCanvasBlurObserver = null;
  46556. }
  46557. this._keys = [];
  46558. };
  46559. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46560. if (this._onKeyboardObserver) {
  46561. var camera = this.camera;
  46562. // Keyboard
  46563. for (var index = 0; index < this._keys.length; index++) {
  46564. var keyCode = this._keys[index];
  46565. var speed = camera._computeLocalCameraSpeed();
  46566. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46567. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46568. }
  46569. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46570. camera._localDirection.copyFromFloats(0, 0, speed);
  46571. }
  46572. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46573. camera._localDirection.copyFromFloats(speed, 0, 0);
  46574. }
  46575. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46576. camera._localDirection.copyFromFloats(0, 0, -speed);
  46577. }
  46578. if (camera.getScene().useRightHandedSystem) {
  46579. camera._localDirection.z *= -1;
  46580. }
  46581. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46582. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46583. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46584. }
  46585. }
  46586. };
  46587. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46588. return "FreeCameraKeyboardMoveInput";
  46589. };
  46590. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46591. this._keys = [];
  46592. };
  46593. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46594. return "keyboard";
  46595. };
  46596. __decorate([
  46597. BABYLON.serialize()
  46598. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46599. __decorate([
  46600. BABYLON.serialize()
  46601. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46602. __decorate([
  46603. BABYLON.serialize()
  46604. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46605. __decorate([
  46606. BABYLON.serialize()
  46607. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46608. return FreeCameraKeyboardMoveInput;
  46609. }());
  46610. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46611. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46612. })(BABYLON || (BABYLON = {}));
  46613. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46614. var BABYLON;
  46615. (function (BABYLON) {
  46616. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46617. __extends(FreeCameraInputsManager, _super);
  46618. function FreeCameraInputsManager(camera) {
  46619. return _super.call(this, camera) || this;
  46620. }
  46621. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46622. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46623. return this;
  46624. };
  46625. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46626. if (touchEnabled === void 0) { touchEnabled = true; }
  46627. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46628. return this;
  46629. };
  46630. FreeCameraInputsManager.prototype.addGamepad = function () {
  46631. this.add(new BABYLON.FreeCameraGamepadInput());
  46632. return this;
  46633. };
  46634. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46635. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46636. return this;
  46637. };
  46638. FreeCameraInputsManager.prototype.addTouch = function () {
  46639. this.add(new BABYLON.FreeCameraTouchInput());
  46640. return this;
  46641. };
  46642. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46643. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46644. return this;
  46645. };
  46646. return FreeCameraInputsManager;
  46647. }(BABYLON.CameraInputsManager));
  46648. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46649. })(BABYLON || (BABYLON = {}));
  46650. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46651. var BABYLON;
  46652. (function (BABYLON) {
  46653. var FreeCamera = /** @class */ (function (_super) {
  46654. __extends(FreeCamera, _super);
  46655. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46656. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46657. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46658. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46659. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46660. _this.checkCollisions = false;
  46661. _this.applyGravity = false;
  46662. _this._needMoveForGravity = false;
  46663. _this._oldPosition = BABYLON.Vector3.Zero();
  46664. _this._diffPosition = BABYLON.Vector3.Zero();
  46665. _this._newPosition = BABYLON.Vector3.Zero();
  46666. // Collisions
  46667. _this._collisionMask = -1;
  46668. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46669. if (collidedMesh === void 0) { collidedMesh = null; }
  46670. //TODO move this to the collision coordinator!
  46671. if (_this.getScene().workerCollisions)
  46672. newPosition.multiplyInPlace(_this._collider._radius);
  46673. var updatePosition = function (newPos) {
  46674. _this._newPosition.copyFrom(newPos);
  46675. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46676. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46677. _this.position.addInPlace(_this._diffPosition);
  46678. if (_this.onCollide && collidedMesh) {
  46679. _this.onCollide(collidedMesh);
  46680. }
  46681. }
  46682. };
  46683. updatePosition(newPosition);
  46684. };
  46685. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46686. _this.inputs.addKeyboard().addMouse();
  46687. return _this;
  46688. }
  46689. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46690. //-- begin properties for backward compatibility for inputs
  46691. /**
  46692. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46693. * Higher values reduce sensitivity.
  46694. */
  46695. get: function () {
  46696. var mouse = this.inputs.attached["mouse"];
  46697. if (mouse)
  46698. return mouse.angularSensibility;
  46699. return 0;
  46700. },
  46701. /**
  46702. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46703. * Higher values reduce sensitivity.
  46704. */
  46705. set: function (value) {
  46706. var mouse = this.inputs.attached["mouse"];
  46707. if (mouse)
  46708. mouse.angularSensibility = value;
  46709. },
  46710. enumerable: true,
  46711. configurable: true
  46712. });
  46713. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46714. get: function () {
  46715. var keyboard = this.inputs.attached["keyboard"];
  46716. if (keyboard)
  46717. return keyboard.keysUp;
  46718. return [];
  46719. },
  46720. set: function (value) {
  46721. var keyboard = this.inputs.attached["keyboard"];
  46722. if (keyboard)
  46723. keyboard.keysUp = value;
  46724. },
  46725. enumerable: true,
  46726. configurable: true
  46727. });
  46728. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46729. get: function () {
  46730. var keyboard = this.inputs.attached["keyboard"];
  46731. if (keyboard)
  46732. return keyboard.keysDown;
  46733. return [];
  46734. },
  46735. set: function (value) {
  46736. var keyboard = this.inputs.attached["keyboard"];
  46737. if (keyboard)
  46738. keyboard.keysDown = value;
  46739. },
  46740. enumerable: true,
  46741. configurable: true
  46742. });
  46743. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46744. get: function () {
  46745. var keyboard = this.inputs.attached["keyboard"];
  46746. if (keyboard)
  46747. return keyboard.keysLeft;
  46748. return [];
  46749. },
  46750. set: function (value) {
  46751. var keyboard = this.inputs.attached["keyboard"];
  46752. if (keyboard)
  46753. keyboard.keysLeft = value;
  46754. },
  46755. enumerable: true,
  46756. configurable: true
  46757. });
  46758. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46759. get: function () {
  46760. var keyboard = this.inputs.attached["keyboard"];
  46761. if (keyboard)
  46762. return keyboard.keysRight;
  46763. return [];
  46764. },
  46765. set: function (value) {
  46766. var keyboard = this.inputs.attached["keyboard"];
  46767. if (keyboard)
  46768. keyboard.keysRight = value;
  46769. },
  46770. enumerable: true,
  46771. configurable: true
  46772. });
  46773. // Controls
  46774. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46775. this.inputs.attachElement(element, noPreventDefault);
  46776. };
  46777. FreeCamera.prototype.detachControl = function (element) {
  46778. this.inputs.detachElement(element);
  46779. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46780. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46781. };
  46782. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46783. get: function () {
  46784. return this._collisionMask;
  46785. },
  46786. set: function (mask) {
  46787. this._collisionMask = !isNaN(mask) ? mask : -1;
  46788. },
  46789. enumerable: true,
  46790. configurable: true
  46791. });
  46792. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46793. var globalPosition;
  46794. if (this.parent) {
  46795. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46796. }
  46797. else {
  46798. globalPosition = this.position;
  46799. }
  46800. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46801. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46802. if (!this._collider) {
  46803. this._collider = new BABYLON.Collider();
  46804. }
  46805. this._collider._radius = this.ellipsoid;
  46806. this._collider.collisionMask = this._collisionMask;
  46807. //no need for clone, as long as gravity is not on.
  46808. var actualDisplacement = displacement;
  46809. //add gravity to the direction to prevent the dual-collision checking
  46810. if (this.applyGravity) {
  46811. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46812. actualDisplacement = displacement.add(this.getScene().gravity);
  46813. }
  46814. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46815. };
  46816. FreeCamera.prototype._checkInputs = function () {
  46817. if (!this._localDirection) {
  46818. this._localDirection = BABYLON.Vector3.Zero();
  46819. this._transformedDirection = BABYLON.Vector3.Zero();
  46820. }
  46821. this.inputs.checkInputs();
  46822. _super.prototype._checkInputs.call(this);
  46823. };
  46824. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46825. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46826. };
  46827. FreeCamera.prototype._updatePosition = function () {
  46828. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46829. this._collideWithWorld(this.cameraDirection);
  46830. }
  46831. else {
  46832. _super.prototype._updatePosition.call(this);
  46833. }
  46834. };
  46835. FreeCamera.prototype.dispose = function () {
  46836. this.inputs.clear();
  46837. _super.prototype.dispose.call(this);
  46838. };
  46839. FreeCamera.prototype.getClassName = function () {
  46840. return "FreeCamera";
  46841. };
  46842. __decorate([
  46843. BABYLON.serializeAsVector3()
  46844. ], FreeCamera.prototype, "ellipsoid", void 0);
  46845. __decorate([
  46846. BABYLON.serializeAsVector3()
  46847. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46848. __decorate([
  46849. BABYLON.serialize()
  46850. ], FreeCamera.prototype, "checkCollisions", void 0);
  46851. __decorate([
  46852. BABYLON.serialize()
  46853. ], FreeCamera.prototype, "applyGravity", void 0);
  46854. return FreeCamera;
  46855. }(BABYLON.TargetCamera));
  46856. BABYLON.FreeCamera = FreeCamera;
  46857. })(BABYLON || (BABYLON = {}));
  46858. //# sourceMappingURL=babylon.freeCamera.js.map
  46859. var BABYLON;
  46860. (function (BABYLON) {
  46861. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46862. function ArcRotateCameraKeyboardMoveInput() {
  46863. this._keys = new Array();
  46864. this.keysUp = [38];
  46865. this.keysDown = [40];
  46866. this.keysLeft = [37];
  46867. this.keysRight = [39];
  46868. this.keysReset = [220];
  46869. this.panningSensibility = 50.0;
  46870. this.zoomingSensibility = 25.0;
  46871. this.useAltToZoom = true;
  46872. }
  46873. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46874. var _this = this;
  46875. if (this._onCanvasBlurObserver) {
  46876. return;
  46877. }
  46878. this._scene = this.camera.getScene();
  46879. this._engine = this._scene.getEngine();
  46880. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46881. _this._keys = [];
  46882. });
  46883. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46884. var evt = info.event;
  46885. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46886. _this._ctrlPressed = evt.ctrlKey;
  46887. _this._altPressed = evt.altKey;
  46888. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46889. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46890. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46891. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46892. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46893. var index = _this._keys.indexOf(evt.keyCode);
  46894. if (index === -1) {
  46895. _this._keys.push(evt.keyCode);
  46896. }
  46897. if (evt.preventDefault) {
  46898. if (!noPreventDefault) {
  46899. evt.preventDefault();
  46900. }
  46901. }
  46902. }
  46903. }
  46904. else {
  46905. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46906. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46907. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46908. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46909. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46910. var index = _this._keys.indexOf(evt.keyCode);
  46911. if (index >= 0) {
  46912. _this._keys.splice(index, 1);
  46913. }
  46914. if (evt.preventDefault) {
  46915. if (!noPreventDefault) {
  46916. evt.preventDefault();
  46917. }
  46918. }
  46919. }
  46920. }
  46921. });
  46922. };
  46923. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46924. if (this._scene) {
  46925. if (this._onKeyboardObserver) {
  46926. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46927. }
  46928. if (this._onCanvasBlurObserver) {
  46929. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46930. }
  46931. this._onKeyboardObserver = null;
  46932. this._onCanvasBlurObserver = null;
  46933. }
  46934. this._keys = [];
  46935. };
  46936. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46937. if (this._onKeyboardObserver) {
  46938. var camera = this.camera;
  46939. for (var index = 0; index < this._keys.length; index++) {
  46940. var keyCode = this._keys[index];
  46941. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46942. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46943. camera.inertialPanningX -= 1 / this.panningSensibility;
  46944. }
  46945. else {
  46946. camera.inertialAlphaOffset -= 0.01;
  46947. }
  46948. }
  46949. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46950. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46951. camera.inertialPanningY += 1 / this.panningSensibility;
  46952. }
  46953. else if (this._altPressed && this.useAltToZoom) {
  46954. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46955. }
  46956. else {
  46957. camera.inertialBetaOffset -= 0.01;
  46958. }
  46959. }
  46960. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46961. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46962. camera.inertialPanningX += 1 / this.panningSensibility;
  46963. }
  46964. else {
  46965. camera.inertialAlphaOffset += 0.01;
  46966. }
  46967. }
  46968. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46969. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46970. camera.inertialPanningY -= 1 / this.panningSensibility;
  46971. }
  46972. else if (this._altPressed && this.useAltToZoom) {
  46973. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46974. }
  46975. else {
  46976. camera.inertialBetaOffset += 0.01;
  46977. }
  46978. }
  46979. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46980. camera.restoreState();
  46981. }
  46982. }
  46983. }
  46984. };
  46985. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46986. return "ArcRotateCameraKeyboardMoveInput";
  46987. };
  46988. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46989. return "keyboard";
  46990. };
  46991. __decorate([
  46992. BABYLON.serialize()
  46993. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46994. __decorate([
  46995. BABYLON.serialize()
  46996. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46997. __decorate([
  46998. BABYLON.serialize()
  46999. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47000. __decorate([
  47001. BABYLON.serialize()
  47002. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47003. __decorate([
  47004. BABYLON.serialize()
  47005. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47006. __decorate([
  47007. BABYLON.serialize()
  47008. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47009. __decorate([
  47010. BABYLON.serialize()
  47011. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47012. __decorate([
  47013. BABYLON.serialize()
  47014. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47015. return ArcRotateCameraKeyboardMoveInput;
  47016. }());
  47017. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47018. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47019. })(BABYLON || (BABYLON = {}));
  47020. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47021. var BABYLON;
  47022. (function (BABYLON) {
  47023. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47024. function ArcRotateCameraMouseWheelInput() {
  47025. this.wheelPrecision = 3.0;
  47026. /**
  47027. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47028. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47029. */
  47030. this.wheelDeltaPercentage = 0;
  47031. }
  47032. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47033. var _this = this;
  47034. this._wheel = function (p, s) {
  47035. //sanity check - this should be a PointerWheel event.
  47036. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47037. return;
  47038. var event = p.event;
  47039. var delta = 0;
  47040. if (event.wheelDelta) {
  47041. if (_this.wheelDeltaPercentage) {
  47042. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47043. if (event.wheelDelta > 0) {
  47044. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47045. }
  47046. else {
  47047. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47048. }
  47049. }
  47050. else {
  47051. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47052. }
  47053. }
  47054. else if (event.detail) {
  47055. delta = -event.detail / _this.wheelPrecision;
  47056. }
  47057. if (delta)
  47058. _this.camera.inertialRadiusOffset += delta;
  47059. if (event.preventDefault) {
  47060. if (!noPreventDefault) {
  47061. event.preventDefault();
  47062. }
  47063. }
  47064. };
  47065. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47066. };
  47067. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47068. if (this._observer && element) {
  47069. this.camera.getScene().onPointerObservable.remove(this._observer);
  47070. this._observer = null;
  47071. this._wheel = null;
  47072. }
  47073. };
  47074. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47075. return "ArcRotateCameraMouseWheelInput";
  47076. };
  47077. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47078. return "mousewheel";
  47079. };
  47080. __decorate([
  47081. BABYLON.serialize()
  47082. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47083. __decorate([
  47084. BABYLON.serialize()
  47085. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47086. return ArcRotateCameraMouseWheelInput;
  47087. }());
  47088. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47089. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47090. })(BABYLON || (BABYLON = {}));
  47091. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47092. var BABYLON;
  47093. (function (BABYLON) {
  47094. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47095. function ArcRotateCameraPointersInput() {
  47096. this.buttons = [0, 1, 2];
  47097. this.angularSensibilityX = 1000.0;
  47098. this.angularSensibilityY = 1000.0;
  47099. this.pinchPrecision = 12.0;
  47100. /**
  47101. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47102. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47103. */
  47104. this.pinchDeltaPercentage = 0;
  47105. this.panningSensibility = 1000.0;
  47106. this.multiTouchPanning = true;
  47107. this.multiTouchPanAndZoom = true;
  47108. this._isPanClick = false;
  47109. this.pinchInwards = true;
  47110. }
  47111. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47112. var _this = this;
  47113. var engine = this.camera.getEngine();
  47114. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47115. var pointA = null;
  47116. var pointB = null;
  47117. var previousPinchSquaredDistance = 0;
  47118. var initialDistance = 0;
  47119. var twoFingerActivityCount = 0;
  47120. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47121. this._pointerInput = function (p, s) {
  47122. var evt = p.event;
  47123. var isTouch = p.event.pointerType === "touch";
  47124. if (engine.isInVRExclusivePointerMode) {
  47125. return;
  47126. }
  47127. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47128. return;
  47129. }
  47130. var srcElement = (evt.srcElement || evt.target);
  47131. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47132. try {
  47133. srcElement.setPointerCapture(evt.pointerId);
  47134. }
  47135. catch (e) {
  47136. //Nothing to do with the error. Execution will continue.
  47137. }
  47138. // Manage panning with pan button click
  47139. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47140. // manage pointers
  47141. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47142. if (pointA === null) {
  47143. pointA = cacheSoloPointer;
  47144. }
  47145. else if (pointB === null) {
  47146. pointB = cacheSoloPointer;
  47147. }
  47148. if (!noPreventDefault) {
  47149. evt.preventDefault();
  47150. element.focus();
  47151. }
  47152. }
  47153. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47154. _this.camera.restoreState();
  47155. }
  47156. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47157. try {
  47158. srcElement.releasePointerCapture(evt.pointerId);
  47159. }
  47160. catch (e) {
  47161. //Nothing to do with the error.
  47162. }
  47163. cacheSoloPointer = null;
  47164. previousPinchSquaredDistance = 0;
  47165. previousMultiTouchPanPosition.isPaning = false;
  47166. previousMultiTouchPanPosition.isPinching = false;
  47167. twoFingerActivityCount = 0;
  47168. initialDistance = 0;
  47169. if (!isTouch) {
  47170. pointB = null; // Mouse and pen are mono pointer
  47171. }
  47172. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47173. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47174. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47175. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47176. if (engine._badOS) {
  47177. pointA = pointB = null;
  47178. }
  47179. else {
  47180. //only remove the impacted pointer in case of multitouch allowing on most
  47181. //platforms switching from rotate to zoom and pan seamlessly.
  47182. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47183. pointA = pointB;
  47184. pointB = null;
  47185. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47186. }
  47187. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47188. pointB = null;
  47189. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47190. }
  47191. else {
  47192. pointA = pointB = null;
  47193. }
  47194. }
  47195. if (!noPreventDefault) {
  47196. evt.preventDefault();
  47197. }
  47198. }
  47199. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47200. if (!noPreventDefault) {
  47201. evt.preventDefault();
  47202. }
  47203. // One button down
  47204. if (pointA && pointB === null && cacheSoloPointer) {
  47205. if (_this.panningSensibility !== 0 &&
  47206. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47207. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47208. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47209. }
  47210. else {
  47211. var offsetX = evt.clientX - cacheSoloPointer.x;
  47212. var offsetY = evt.clientY - cacheSoloPointer.y;
  47213. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47214. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47215. }
  47216. cacheSoloPointer.x = evt.clientX;
  47217. cacheSoloPointer.y = evt.clientY;
  47218. }
  47219. // Two buttons down: pinch/pan
  47220. else if (pointA && pointB) {
  47221. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47222. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47223. ed.x = evt.clientX;
  47224. ed.y = evt.clientY;
  47225. var direction = _this.pinchInwards ? 1 : -1;
  47226. var distX = pointA.x - pointB.x;
  47227. var distY = pointA.y - pointB.y;
  47228. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47229. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47230. if (previousPinchSquaredDistance === 0) {
  47231. initialDistance = pinchDistance;
  47232. previousPinchSquaredDistance = pinchSquaredDistance;
  47233. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47234. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47235. return;
  47236. }
  47237. if (_this.multiTouchPanAndZoom) {
  47238. if (_this.pinchDeltaPercentage) {
  47239. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47240. }
  47241. else {
  47242. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47243. (_this.pinchPrecision *
  47244. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47245. direction);
  47246. }
  47247. if (_this.panningSensibility !== 0) {
  47248. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47249. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47250. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47251. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47252. previousMultiTouchPanPosition.x = pointersCenterX;
  47253. previousMultiTouchPanPosition.y = pointersCenterY;
  47254. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47255. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47256. }
  47257. }
  47258. else {
  47259. twoFingerActivityCount++;
  47260. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47261. if (_this.pinchDeltaPercentage) {
  47262. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47263. }
  47264. else {
  47265. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47266. (_this.pinchPrecision *
  47267. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47268. direction);
  47269. }
  47270. previousMultiTouchPanPosition.isPaning = false;
  47271. previousMultiTouchPanPosition.isPinching = true;
  47272. }
  47273. else {
  47274. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47275. if (!previousMultiTouchPanPosition.isPaning) {
  47276. previousMultiTouchPanPosition.isPaning = true;
  47277. previousMultiTouchPanPosition.isPinching = false;
  47278. previousMultiTouchPanPosition.x = ed.x;
  47279. previousMultiTouchPanPosition.y = ed.y;
  47280. return;
  47281. }
  47282. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47283. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47284. }
  47285. }
  47286. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47287. previousMultiTouchPanPosition.x = ed.x;
  47288. previousMultiTouchPanPosition.y = ed.y;
  47289. }
  47290. }
  47291. previousPinchSquaredDistance = pinchSquaredDistance;
  47292. }
  47293. }
  47294. };
  47295. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47296. this._onContextMenu = function (evt) {
  47297. evt.preventDefault();
  47298. };
  47299. if (!this.camera._useCtrlForPanning) {
  47300. element.addEventListener("contextmenu", this._onContextMenu, false);
  47301. }
  47302. this._onLostFocus = function () {
  47303. //this._keys = [];
  47304. pointA = pointB = null;
  47305. previousPinchSquaredDistance = 0;
  47306. previousMultiTouchPanPosition.isPaning = false;
  47307. previousMultiTouchPanPosition.isPinching = false;
  47308. twoFingerActivityCount = 0;
  47309. cacheSoloPointer = null;
  47310. initialDistance = 0;
  47311. };
  47312. this._onMouseMove = function (evt) {
  47313. if (!engine.isPointerLock) {
  47314. return;
  47315. }
  47316. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47317. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47318. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47319. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47320. if (!noPreventDefault) {
  47321. evt.preventDefault();
  47322. }
  47323. };
  47324. this._onGestureStart = function (e) {
  47325. if (window.MSGesture === undefined) {
  47326. return;
  47327. }
  47328. if (!_this._MSGestureHandler) {
  47329. _this._MSGestureHandler = new MSGesture();
  47330. _this._MSGestureHandler.target = element;
  47331. }
  47332. _this._MSGestureHandler.addPointer(e.pointerId);
  47333. };
  47334. this._onGesture = function (e) {
  47335. _this.camera.radius *= e.scale;
  47336. if (e.preventDefault) {
  47337. if (!noPreventDefault) {
  47338. e.stopPropagation();
  47339. e.preventDefault();
  47340. }
  47341. }
  47342. };
  47343. element.addEventListener("mousemove", this._onMouseMove, false);
  47344. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47345. element.addEventListener("MSGestureChange", this._onGesture, false);
  47346. BABYLON.Tools.RegisterTopRootEvents([
  47347. { name: "blur", handler: this._onLostFocus }
  47348. ]);
  47349. };
  47350. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47351. if (this._onLostFocus) {
  47352. BABYLON.Tools.UnregisterTopRootEvents([
  47353. { name: "blur", handler: this._onLostFocus }
  47354. ]);
  47355. }
  47356. if (element && this._observer) {
  47357. this.camera.getScene().onPointerObservable.remove(this._observer);
  47358. this._observer = null;
  47359. if (this._onContextMenu) {
  47360. element.removeEventListener("contextmenu", this._onContextMenu);
  47361. }
  47362. if (this._onMouseMove) {
  47363. element.removeEventListener("mousemove", this._onMouseMove);
  47364. }
  47365. if (this._onGestureStart) {
  47366. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47367. }
  47368. if (this._onGesture) {
  47369. element.removeEventListener("MSGestureChange", this._onGesture);
  47370. }
  47371. this._isPanClick = false;
  47372. this.pinchInwards = true;
  47373. this._onMouseMove = null;
  47374. this._onGestureStart = null;
  47375. this._onGesture = null;
  47376. this._MSGestureHandler = null;
  47377. this._onLostFocus = null;
  47378. this._onContextMenu = null;
  47379. }
  47380. };
  47381. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47382. return "ArcRotateCameraPointersInput";
  47383. };
  47384. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47385. return "pointers";
  47386. };
  47387. __decorate([
  47388. BABYLON.serialize()
  47389. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47390. __decorate([
  47391. BABYLON.serialize()
  47392. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47393. __decorate([
  47394. BABYLON.serialize()
  47395. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47396. __decorate([
  47397. BABYLON.serialize()
  47398. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47399. __decorate([
  47400. BABYLON.serialize()
  47401. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47402. __decorate([
  47403. BABYLON.serialize()
  47404. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47405. __decorate([
  47406. BABYLON.serialize()
  47407. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47408. __decorate([
  47409. BABYLON.serialize()
  47410. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47411. return ArcRotateCameraPointersInput;
  47412. }());
  47413. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47414. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47415. })(BABYLON || (BABYLON = {}));
  47416. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47417. var BABYLON;
  47418. (function (BABYLON) {
  47419. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47420. __extends(ArcRotateCameraInputsManager, _super);
  47421. function ArcRotateCameraInputsManager(camera) {
  47422. return _super.call(this, camera) || this;
  47423. }
  47424. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47425. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47426. return this;
  47427. };
  47428. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47429. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47430. return this;
  47431. };
  47432. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47433. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47434. return this;
  47435. };
  47436. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47437. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47438. return this;
  47439. };
  47440. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47441. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47442. return this;
  47443. };
  47444. return ArcRotateCameraInputsManager;
  47445. }(BABYLON.CameraInputsManager));
  47446. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47447. })(BABYLON || (BABYLON = {}));
  47448. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47449. var BABYLON;
  47450. (function (BABYLON) {
  47451. var ArcRotateCamera = /** @class */ (function (_super) {
  47452. __extends(ArcRotateCamera, _super);
  47453. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47454. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47455. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47456. _this.inertialAlphaOffset = 0;
  47457. _this.inertialBetaOffset = 0;
  47458. _this.inertialRadiusOffset = 0;
  47459. _this.lowerAlphaLimit = null;
  47460. _this.upperAlphaLimit = null;
  47461. _this.lowerBetaLimit = 0.01;
  47462. _this.upperBetaLimit = Math.PI;
  47463. _this.lowerRadiusLimit = null;
  47464. _this.upperRadiusLimit = null;
  47465. _this.inertialPanningX = 0;
  47466. _this.inertialPanningY = 0;
  47467. _this.pinchToPanMaxDistance = 20;
  47468. _this.panningDistanceLimit = null;
  47469. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47470. _this.panningInertia = 0.9;
  47471. //-- end properties for backward compatibility for inputs
  47472. _this.zoomOnFactor = 1;
  47473. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47474. _this.allowUpsideDown = true;
  47475. _this._viewMatrix = new BABYLON.Matrix();
  47476. // Panning
  47477. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47478. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47479. _this.checkCollisions = false;
  47480. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47481. _this._previousPosition = BABYLON.Vector3.Zero();
  47482. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47483. _this._newPosition = BABYLON.Vector3.Zero();
  47484. _this._computationVector = BABYLON.Vector3.Zero();
  47485. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47486. if (collidedMesh === void 0) { collidedMesh = null; }
  47487. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47488. newPosition.multiplyInPlace(_this._collider._radius);
  47489. }
  47490. if (!collidedMesh) {
  47491. _this._previousPosition.copyFrom(_this.position);
  47492. }
  47493. else {
  47494. _this.setPosition(newPosition);
  47495. if (_this.onCollide) {
  47496. _this.onCollide(collidedMesh);
  47497. }
  47498. }
  47499. // Recompute because of constraints
  47500. var cosa = Math.cos(_this.alpha);
  47501. var sina = Math.sin(_this.alpha);
  47502. var cosb = Math.cos(_this.beta);
  47503. var sinb = Math.sin(_this.beta);
  47504. if (sinb === 0) {
  47505. sinb = 0.0001;
  47506. }
  47507. var target = _this._getTargetPosition();
  47508. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47509. target.addToRef(_this._computationVector, _this._newPosition);
  47510. _this.position.copyFrom(_this._newPosition);
  47511. var up = _this.upVector;
  47512. if (_this.allowUpsideDown && _this.beta < 0) {
  47513. up = up.clone();
  47514. up = up.negate();
  47515. }
  47516. _this._computeViewMatrix(_this.position, target, up);
  47517. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47518. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47519. _this._collisionTriggered = false;
  47520. };
  47521. _this._target = BABYLON.Vector3.Zero();
  47522. if (target) {
  47523. _this.setTarget(target);
  47524. }
  47525. _this.alpha = alpha;
  47526. _this.beta = beta;
  47527. _this.radius = radius;
  47528. _this.getViewMatrix();
  47529. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47530. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47531. return _this;
  47532. }
  47533. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47534. get: function () {
  47535. return this._target;
  47536. },
  47537. set: function (value) {
  47538. this.setTarget(value);
  47539. },
  47540. enumerable: true,
  47541. configurable: true
  47542. });
  47543. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47544. //-- begin properties for backward compatibility for inputs
  47545. get: function () {
  47546. var pointers = this.inputs.attached["pointers"];
  47547. if (pointers)
  47548. return pointers.angularSensibilityX;
  47549. return 0;
  47550. },
  47551. set: function (value) {
  47552. var pointers = this.inputs.attached["pointers"];
  47553. if (pointers) {
  47554. pointers.angularSensibilityX = value;
  47555. }
  47556. },
  47557. enumerable: true,
  47558. configurable: true
  47559. });
  47560. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47561. get: function () {
  47562. var pointers = this.inputs.attached["pointers"];
  47563. if (pointers)
  47564. return pointers.angularSensibilityY;
  47565. return 0;
  47566. },
  47567. set: function (value) {
  47568. var pointers = this.inputs.attached["pointers"];
  47569. if (pointers) {
  47570. pointers.angularSensibilityY = value;
  47571. }
  47572. },
  47573. enumerable: true,
  47574. configurable: true
  47575. });
  47576. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47577. get: function () {
  47578. var pointers = this.inputs.attached["pointers"];
  47579. if (pointers)
  47580. return pointers.pinchPrecision;
  47581. return 0;
  47582. },
  47583. set: function (value) {
  47584. var pointers = this.inputs.attached["pointers"];
  47585. if (pointers) {
  47586. pointers.pinchPrecision = value;
  47587. }
  47588. },
  47589. enumerable: true,
  47590. configurable: true
  47591. });
  47592. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47593. get: function () {
  47594. var pointers = this.inputs.attached["pointers"];
  47595. if (pointers)
  47596. return pointers.pinchDeltaPercentage;
  47597. return 0;
  47598. },
  47599. set: function (value) {
  47600. var pointers = this.inputs.attached["pointers"];
  47601. if (pointers) {
  47602. pointers.pinchDeltaPercentage = value;
  47603. }
  47604. },
  47605. enumerable: true,
  47606. configurable: true
  47607. });
  47608. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47609. get: function () {
  47610. var pointers = this.inputs.attached["pointers"];
  47611. if (pointers)
  47612. return pointers.panningSensibility;
  47613. return 0;
  47614. },
  47615. set: function (value) {
  47616. var pointers = this.inputs.attached["pointers"];
  47617. if (pointers) {
  47618. pointers.panningSensibility = value;
  47619. }
  47620. },
  47621. enumerable: true,
  47622. configurable: true
  47623. });
  47624. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47625. get: function () {
  47626. var keyboard = this.inputs.attached["keyboard"];
  47627. if (keyboard)
  47628. return keyboard.keysUp;
  47629. return [];
  47630. },
  47631. set: function (value) {
  47632. var keyboard = this.inputs.attached["keyboard"];
  47633. if (keyboard)
  47634. keyboard.keysUp = value;
  47635. },
  47636. enumerable: true,
  47637. configurable: true
  47638. });
  47639. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47640. get: function () {
  47641. var keyboard = this.inputs.attached["keyboard"];
  47642. if (keyboard)
  47643. return keyboard.keysDown;
  47644. return [];
  47645. },
  47646. set: function (value) {
  47647. var keyboard = this.inputs.attached["keyboard"];
  47648. if (keyboard)
  47649. keyboard.keysDown = value;
  47650. },
  47651. enumerable: true,
  47652. configurable: true
  47653. });
  47654. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47655. get: function () {
  47656. var keyboard = this.inputs.attached["keyboard"];
  47657. if (keyboard)
  47658. return keyboard.keysLeft;
  47659. return [];
  47660. },
  47661. set: function (value) {
  47662. var keyboard = this.inputs.attached["keyboard"];
  47663. if (keyboard)
  47664. keyboard.keysLeft = value;
  47665. },
  47666. enumerable: true,
  47667. configurable: true
  47668. });
  47669. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47670. get: function () {
  47671. var keyboard = this.inputs.attached["keyboard"];
  47672. if (keyboard)
  47673. return keyboard.keysRight;
  47674. return [];
  47675. },
  47676. set: function (value) {
  47677. var keyboard = this.inputs.attached["keyboard"];
  47678. if (keyboard)
  47679. keyboard.keysRight = value;
  47680. },
  47681. enumerable: true,
  47682. configurable: true
  47683. });
  47684. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47685. get: function () {
  47686. var mousewheel = this.inputs.attached["mousewheel"];
  47687. if (mousewheel)
  47688. return mousewheel.wheelPrecision;
  47689. return 0;
  47690. },
  47691. set: function (value) {
  47692. var mousewheel = this.inputs.attached["mousewheel"];
  47693. if (mousewheel)
  47694. mousewheel.wheelPrecision = value;
  47695. },
  47696. enumerable: true,
  47697. configurable: true
  47698. });
  47699. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47700. get: function () {
  47701. var mousewheel = this.inputs.attached["mousewheel"];
  47702. if (mousewheel)
  47703. return mousewheel.wheelDeltaPercentage;
  47704. return 0;
  47705. },
  47706. set: function (value) {
  47707. var mousewheel = this.inputs.attached["mousewheel"];
  47708. if (mousewheel)
  47709. mousewheel.wheelDeltaPercentage = value;
  47710. },
  47711. enumerable: true,
  47712. configurable: true
  47713. });
  47714. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47715. get: function () {
  47716. return this._bouncingBehavior;
  47717. },
  47718. enumerable: true,
  47719. configurable: true
  47720. });
  47721. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47722. get: function () {
  47723. return this._bouncingBehavior != null;
  47724. },
  47725. set: function (value) {
  47726. if (value === this.useBouncingBehavior) {
  47727. return;
  47728. }
  47729. if (value) {
  47730. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47731. this.addBehavior(this._bouncingBehavior);
  47732. }
  47733. else if (this._bouncingBehavior) {
  47734. this.removeBehavior(this._bouncingBehavior);
  47735. this._bouncingBehavior = null;
  47736. }
  47737. },
  47738. enumerable: true,
  47739. configurable: true
  47740. });
  47741. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47742. get: function () {
  47743. return this._framingBehavior;
  47744. },
  47745. enumerable: true,
  47746. configurable: true
  47747. });
  47748. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47749. get: function () {
  47750. return this._framingBehavior != null;
  47751. },
  47752. set: function (value) {
  47753. if (value === this.useFramingBehavior) {
  47754. return;
  47755. }
  47756. if (value) {
  47757. this._framingBehavior = new BABYLON.FramingBehavior();
  47758. this.addBehavior(this._framingBehavior);
  47759. }
  47760. else if (this._framingBehavior) {
  47761. this.removeBehavior(this._framingBehavior);
  47762. this._framingBehavior = null;
  47763. }
  47764. },
  47765. enumerable: true,
  47766. configurable: true
  47767. });
  47768. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47769. get: function () {
  47770. return this._autoRotationBehavior;
  47771. },
  47772. enumerable: true,
  47773. configurable: true
  47774. });
  47775. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47776. get: function () {
  47777. return this._autoRotationBehavior != null;
  47778. },
  47779. set: function (value) {
  47780. if (value === this.useAutoRotationBehavior) {
  47781. return;
  47782. }
  47783. if (value) {
  47784. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47785. this.addBehavior(this._autoRotationBehavior);
  47786. }
  47787. else if (this._autoRotationBehavior) {
  47788. this.removeBehavior(this._autoRotationBehavior);
  47789. this._autoRotationBehavior = null;
  47790. }
  47791. },
  47792. enumerable: true,
  47793. configurable: true
  47794. });
  47795. // Cache
  47796. ArcRotateCamera.prototype._initCache = function () {
  47797. _super.prototype._initCache.call(this);
  47798. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47799. this._cache.alpha = undefined;
  47800. this._cache.beta = undefined;
  47801. this._cache.radius = undefined;
  47802. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47803. };
  47804. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47805. if (!ignoreParentClass) {
  47806. _super.prototype._updateCache.call(this);
  47807. }
  47808. this._cache._target.copyFrom(this._getTargetPosition());
  47809. this._cache.alpha = this.alpha;
  47810. this._cache.beta = this.beta;
  47811. this._cache.radius = this.radius;
  47812. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47813. };
  47814. ArcRotateCamera.prototype._getTargetPosition = function () {
  47815. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47816. var pos = this._targetHost.getAbsolutePosition();
  47817. if (this._targetBoundingCenter) {
  47818. pos.addToRef(this._targetBoundingCenter, this._target);
  47819. }
  47820. else {
  47821. this._target.copyFrom(pos);
  47822. }
  47823. }
  47824. var lockedTargetPosition = this._getLockedTargetPosition();
  47825. if (lockedTargetPosition) {
  47826. return lockedTargetPosition;
  47827. }
  47828. return this._target;
  47829. };
  47830. ArcRotateCamera.prototype.storeState = function () {
  47831. this._storedAlpha = this.alpha;
  47832. this._storedBeta = this.beta;
  47833. this._storedRadius = this.radius;
  47834. this._storedTarget = this._getTargetPosition().clone();
  47835. return _super.prototype.storeState.call(this);
  47836. };
  47837. /**
  47838. * Restored camera state. You must call storeState() first
  47839. */
  47840. ArcRotateCamera.prototype._restoreStateValues = function () {
  47841. if (!_super.prototype._restoreStateValues.call(this)) {
  47842. return false;
  47843. }
  47844. this.alpha = this._storedAlpha;
  47845. this.beta = this._storedBeta;
  47846. this.radius = this._storedRadius;
  47847. this.setTarget(this._storedTarget.clone());
  47848. this.inertialAlphaOffset = 0;
  47849. this.inertialBetaOffset = 0;
  47850. this.inertialRadiusOffset = 0;
  47851. this.inertialPanningX = 0;
  47852. this.inertialPanningY = 0;
  47853. return true;
  47854. };
  47855. // Synchronized
  47856. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47857. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47858. return false;
  47859. return this._cache._target.equals(this._getTargetPosition())
  47860. && this._cache.alpha === this.alpha
  47861. && this._cache.beta === this.beta
  47862. && this._cache.radius === this.radius
  47863. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47864. };
  47865. // Methods
  47866. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47867. var _this = this;
  47868. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47869. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47870. this._useCtrlForPanning = useCtrlForPanning;
  47871. this._panningMouseButton = panningMouseButton;
  47872. this.inputs.attachElement(element, noPreventDefault);
  47873. this._reset = function () {
  47874. _this.inertialAlphaOffset = 0;
  47875. _this.inertialBetaOffset = 0;
  47876. _this.inertialRadiusOffset = 0;
  47877. _this.inertialPanningX = 0;
  47878. _this.inertialPanningY = 0;
  47879. };
  47880. };
  47881. ArcRotateCamera.prototype.detachControl = function (element) {
  47882. this.inputs.detachElement(element);
  47883. if (this._reset) {
  47884. this._reset();
  47885. }
  47886. };
  47887. ArcRotateCamera.prototype._checkInputs = function () {
  47888. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47889. if (this._collisionTriggered) {
  47890. return;
  47891. }
  47892. this.inputs.checkInputs();
  47893. // Inertia
  47894. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47895. var inertialAlphaOffset = this.inertialAlphaOffset;
  47896. if (this.beta <= 0)
  47897. inertialAlphaOffset *= -1;
  47898. if (this.getScene().useRightHandedSystem)
  47899. inertialAlphaOffset *= -1;
  47900. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47901. inertialAlphaOffset *= -1;
  47902. this.alpha += inertialAlphaOffset;
  47903. this.beta += this.inertialBetaOffset;
  47904. this.radius -= this.inertialRadiusOffset;
  47905. this.inertialAlphaOffset *= this.inertia;
  47906. this.inertialBetaOffset *= this.inertia;
  47907. this.inertialRadiusOffset *= this.inertia;
  47908. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47909. this.inertialAlphaOffset = 0;
  47910. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47911. this.inertialBetaOffset = 0;
  47912. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47913. this.inertialRadiusOffset = 0;
  47914. }
  47915. // Panning inertia
  47916. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47917. if (!this._localDirection) {
  47918. this._localDirection = BABYLON.Vector3.Zero();
  47919. this._transformedDirection = BABYLON.Vector3.Zero();
  47920. }
  47921. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47922. this._localDirection.multiplyInPlace(this.panningAxis);
  47923. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47924. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47925. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47926. if (!this.panningAxis.y) {
  47927. this._transformedDirection.y = 0;
  47928. }
  47929. if (!this._targetHost) {
  47930. if (this.panningDistanceLimit) {
  47931. this._transformedDirection.addInPlace(this._target);
  47932. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47933. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47934. this._target.copyFrom(this._transformedDirection);
  47935. }
  47936. }
  47937. else {
  47938. this._target.addInPlace(this._transformedDirection);
  47939. }
  47940. }
  47941. this.inertialPanningX *= this.panningInertia;
  47942. this.inertialPanningY *= this.panningInertia;
  47943. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47944. this.inertialPanningX = 0;
  47945. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47946. this.inertialPanningY = 0;
  47947. }
  47948. // Limits
  47949. this._checkLimits();
  47950. _super.prototype._checkInputs.call(this);
  47951. };
  47952. ArcRotateCamera.prototype._checkLimits = function () {
  47953. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47954. if (this.allowUpsideDown && this.beta > Math.PI) {
  47955. this.beta = this.beta - (2 * Math.PI);
  47956. }
  47957. }
  47958. else {
  47959. if (this.beta < this.lowerBetaLimit) {
  47960. this.beta = this.lowerBetaLimit;
  47961. }
  47962. }
  47963. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47964. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47965. this.beta = this.beta + (2 * Math.PI);
  47966. }
  47967. }
  47968. else {
  47969. if (this.beta > this.upperBetaLimit) {
  47970. this.beta = this.upperBetaLimit;
  47971. }
  47972. }
  47973. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  47974. this.alpha = this.lowerAlphaLimit;
  47975. }
  47976. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  47977. this.alpha = this.upperAlphaLimit;
  47978. }
  47979. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  47980. this.radius = this.lowerRadiusLimit;
  47981. }
  47982. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  47983. this.radius = this.upperRadiusLimit;
  47984. }
  47985. };
  47986. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47987. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47988. this.radius = this._computationVector.length();
  47989. if (this.radius === 0) {
  47990. this.radius = 0.0001; // Just to avoid division by zero
  47991. }
  47992. // Alpha
  47993. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47994. if (this._computationVector.z < 0) {
  47995. this.alpha = 2 * Math.PI - this.alpha;
  47996. }
  47997. // Beta
  47998. this.beta = Math.acos(this._computationVector.y / this.radius);
  47999. this._checkLimits();
  48000. };
  48001. ArcRotateCamera.prototype.setPosition = function (position) {
  48002. if (this.position.equals(position)) {
  48003. return;
  48004. }
  48005. this.position.copyFrom(position);
  48006. this.rebuildAnglesAndRadius();
  48007. };
  48008. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48009. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48010. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48011. if (target.getBoundingInfo) {
  48012. if (toBoundingCenter) {
  48013. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48014. }
  48015. else {
  48016. this._targetBoundingCenter = null;
  48017. }
  48018. this._targetHost = target;
  48019. this._target = this._getTargetPosition();
  48020. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48021. }
  48022. else {
  48023. var newTarget = target;
  48024. var currentTarget = this._getTargetPosition();
  48025. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48026. return;
  48027. }
  48028. this._targetHost = null;
  48029. this._target = newTarget;
  48030. this._targetBoundingCenter = null;
  48031. this.onMeshTargetChangedObservable.notifyObservers(null);
  48032. }
  48033. this.rebuildAnglesAndRadius();
  48034. };
  48035. ArcRotateCamera.prototype._getViewMatrix = function () {
  48036. // Compute
  48037. var cosa = Math.cos(this.alpha);
  48038. var sina = Math.sin(this.alpha);
  48039. var cosb = Math.cos(this.beta);
  48040. var sinb = Math.sin(this.beta);
  48041. if (sinb === 0) {
  48042. sinb = 0.0001;
  48043. }
  48044. var target = this._getTargetPosition();
  48045. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48046. target.addToRef(this._computationVector, this._newPosition);
  48047. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48048. if (!this._collider) {
  48049. this._collider = new BABYLON.Collider();
  48050. }
  48051. this._collider._radius = this.collisionRadius;
  48052. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48053. this._collisionTriggered = true;
  48054. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48055. }
  48056. else {
  48057. this.position.copyFrom(this._newPosition);
  48058. var up = this.upVector;
  48059. if (this.allowUpsideDown && sinb < 0) {
  48060. up = up.clone();
  48061. up = up.negate();
  48062. }
  48063. this._computeViewMatrix(this.position, target, up);
  48064. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48065. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48066. }
  48067. this._currentTarget = target;
  48068. return this._viewMatrix;
  48069. };
  48070. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48071. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48072. meshes = meshes || this.getScene().meshes;
  48073. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48074. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48075. this.radius = distance * this.zoomOnFactor;
  48076. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48077. };
  48078. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48079. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48080. var meshesOrMinMaxVector;
  48081. var distance;
  48082. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48083. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48084. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48085. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48086. }
  48087. else { //minMaxVector and distance
  48088. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48089. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48090. distance = minMaxVectorAndDistance.distance;
  48091. }
  48092. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48093. if (!doNotUpdateMaxZ) {
  48094. this.maxZ = distance * 2;
  48095. }
  48096. };
  48097. /**
  48098. * @override
  48099. * Override Camera.createRigCamera
  48100. */
  48101. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48102. var alphaShift = 0;
  48103. switch (this.cameraRigMode) {
  48104. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48105. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48106. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48107. case BABYLON.Camera.RIG_MODE_VR:
  48108. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48109. break;
  48110. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48111. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48112. break;
  48113. }
  48114. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48115. rigCam._cameraRigParams = {};
  48116. return rigCam;
  48117. };
  48118. /**
  48119. * @override
  48120. * Override Camera._updateRigCameras
  48121. */
  48122. ArcRotateCamera.prototype._updateRigCameras = function () {
  48123. var camLeft = this._rigCameras[0];
  48124. var camRight = this._rigCameras[1];
  48125. camLeft.beta = camRight.beta = this.beta;
  48126. camLeft.radius = camRight.radius = this.radius;
  48127. switch (this.cameraRigMode) {
  48128. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48129. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48130. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48131. case BABYLON.Camera.RIG_MODE_VR:
  48132. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48133. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48134. break;
  48135. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48136. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48137. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48138. break;
  48139. }
  48140. _super.prototype._updateRigCameras.call(this);
  48141. };
  48142. ArcRotateCamera.prototype.dispose = function () {
  48143. this.inputs.clear();
  48144. _super.prototype.dispose.call(this);
  48145. };
  48146. ArcRotateCamera.prototype.getClassName = function () {
  48147. return "ArcRotateCamera";
  48148. };
  48149. __decorate([
  48150. BABYLON.serialize()
  48151. ], ArcRotateCamera.prototype, "alpha", void 0);
  48152. __decorate([
  48153. BABYLON.serialize()
  48154. ], ArcRotateCamera.prototype, "beta", void 0);
  48155. __decorate([
  48156. BABYLON.serialize()
  48157. ], ArcRotateCamera.prototype, "radius", void 0);
  48158. __decorate([
  48159. BABYLON.serializeAsVector3("target")
  48160. ], ArcRotateCamera.prototype, "_target", void 0);
  48161. __decorate([
  48162. BABYLON.serialize()
  48163. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48164. __decorate([
  48165. BABYLON.serialize()
  48166. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48167. __decorate([
  48168. BABYLON.serialize()
  48169. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48170. __decorate([
  48171. BABYLON.serialize()
  48172. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48173. __decorate([
  48174. BABYLON.serialize()
  48175. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48176. __decorate([
  48177. BABYLON.serialize()
  48178. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48179. __decorate([
  48180. BABYLON.serialize()
  48181. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48182. __decorate([
  48183. BABYLON.serialize()
  48184. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48185. __decorate([
  48186. BABYLON.serialize()
  48187. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48188. __decorate([
  48189. BABYLON.serialize()
  48190. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48191. __decorate([
  48192. BABYLON.serialize()
  48193. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48194. __decorate([
  48195. BABYLON.serialize()
  48196. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48197. __decorate([
  48198. BABYLON.serialize()
  48199. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48200. __decorate([
  48201. BABYLON.serializeAsVector3()
  48202. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48203. __decorate([
  48204. BABYLON.serialize()
  48205. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48206. __decorate([
  48207. BABYLON.serialize()
  48208. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48209. __decorate([
  48210. BABYLON.serialize()
  48211. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48212. return ArcRotateCamera;
  48213. }(BABYLON.TargetCamera));
  48214. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48215. })(BABYLON || (BABYLON = {}));
  48216. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48217. var BABYLON;
  48218. (function (BABYLON) {
  48219. /**
  48220. * The HemisphericLight simulates the ambient environment light,
  48221. * so the passed direction is the light reflection direction, not the incoming direction.
  48222. */
  48223. var HemisphericLight = /** @class */ (function (_super) {
  48224. __extends(HemisphericLight, _super);
  48225. /**
  48226. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48227. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48228. * The HemisphericLight can't cast shadows.
  48229. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48230. * @param name The friendly name of the light
  48231. * @param direction The direction of the light reflection
  48232. * @param scene The scene the light belongs to
  48233. */
  48234. function HemisphericLight(name, direction, scene) {
  48235. var _this = _super.call(this, name, scene) || this;
  48236. /**
  48237. * The groundColor is the light in the opposite direction to the one specified during creation.
  48238. * 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.
  48239. */
  48240. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48241. _this.direction = direction || BABYLON.Vector3.Up();
  48242. return _this;
  48243. }
  48244. HemisphericLight.prototype._buildUniformLayout = function () {
  48245. this._uniformBuffer.addUniform("vLightData", 4);
  48246. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48247. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48248. this._uniformBuffer.addUniform("vLightGround", 3);
  48249. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48250. this._uniformBuffer.addUniform("depthValues", 2);
  48251. this._uniformBuffer.create();
  48252. };
  48253. /**
  48254. * Returns the string "HemisphericLight".
  48255. * @return The class name
  48256. */
  48257. HemisphericLight.prototype.getClassName = function () {
  48258. return "HemisphericLight";
  48259. };
  48260. /**
  48261. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48262. * Returns the updated direction.
  48263. * @param target The target the direction should point to
  48264. * @return The computed direction
  48265. */
  48266. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48267. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48268. return this.direction;
  48269. };
  48270. /**
  48271. * Returns the shadow generator associated to the light.
  48272. * @returns Always null for hemispheric lights because it does not support shadows.
  48273. */
  48274. HemisphericLight.prototype.getShadowGenerator = function () {
  48275. return null;
  48276. };
  48277. /**
  48278. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48279. * @param effect The effect to update
  48280. * @param lightIndex The index of the light in the effect to update
  48281. * @returns The hemispheric light
  48282. */
  48283. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48284. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48285. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48286. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48287. return this;
  48288. };
  48289. /**
  48290. * @hidden internal use only.
  48291. */
  48292. HemisphericLight.prototype._getWorldMatrix = function () {
  48293. if (!this._worldMatrix) {
  48294. this._worldMatrix = BABYLON.Matrix.Identity();
  48295. }
  48296. return this._worldMatrix;
  48297. };
  48298. /**
  48299. * Returns the integer 3.
  48300. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48301. */
  48302. HemisphericLight.prototype.getTypeID = function () {
  48303. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48304. };
  48305. __decorate([
  48306. BABYLON.serializeAsColor3()
  48307. ], HemisphericLight.prototype, "groundColor", void 0);
  48308. __decorate([
  48309. BABYLON.serializeAsVector3()
  48310. ], HemisphericLight.prototype, "direction", void 0);
  48311. return HemisphericLight;
  48312. }(BABYLON.Light));
  48313. BABYLON.HemisphericLight = HemisphericLight;
  48314. })(BABYLON || (BABYLON = {}));
  48315. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48316. var BABYLON;
  48317. (function (BABYLON) {
  48318. /**
  48319. * Base implementation IShadowLight
  48320. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48321. */
  48322. var ShadowLight = /** @class */ (function (_super) {
  48323. __extends(ShadowLight, _super);
  48324. function ShadowLight() {
  48325. var _this = _super !== null && _super.apply(this, arguments) || this;
  48326. _this._needProjectionMatrixCompute = true;
  48327. return _this;
  48328. }
  48329. ShadowLight.prototype._setPosition = function (value) {
  48330. this._position = value;
  48331. };
  48332. Object.defineProperty(ShadowLight.prototype, "position", {
  48333. /**
  48334. * Sets the position the shadow will be casted from. Also use as the light position for both
  48335. * point and spot lights.
  48336. */
  48337. get: function () {
  48338. return this._position;
  48339. },
  48340. /**
  48341. * Sets the position the shadow will be casted from. Also use as the light position for both
  48342. * point and spot lights.
  48343. */
  48344. set: function (value) {
  48345. this._setPosition(value);
  48346. },
  48347. enumerable: true,
  48348. configurable: true
  48349. });
  48350. ShadowLight.prototype._setDirection = function (value) {
  48351. this._direction = value;
  48352. };
  48353. Object.defineProperty(ShadowLight.prototype, "direction", {
  48354. /**
  48355. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48356. * Also use as the light direction on spot and directional lights.
  48357. */
  48358. get: function () {
  48359. return this._direction;
  48360. },
  48361. /**
  48362. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48363. * Also use as the light direction on spot and directional lights.
  48364. */
  48365. set: function (value) {
  48366. this._setDirection(value);
  48367. },
  48368. enumerable: true,
  48369. configurable: true
  48370. });
  48371. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48372. /**
  48373. * Gets the shadow projection clipping minimum z value.
  48374. */
  48375. get: function () {
  48376. return this._shadowMinZ;
  48377. },
  48378. /**
  48379. * Sets the shadow projection clipping minimum z value.
  48380. */
  48381. set: function (value) {
  48382. this._shadowMinZ = value;
  48383. this.forceProjectionMatrixCompute();
  48384. },
  48385. enumerable: true,
  48386. configurable: true
  48387. });
  48388. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48389. /**
  48390. * Sets the shadow projection clipping maximum z value.
  48391. */
  48392. get: function () {
  48393. return this._shadowMaxZ;
  48394. },
  48395. /**
  48396. * Gets the shadow projection clipping maximum z value.
  48397. */
  48398. set: function (value) {
  48399. this._shadowMaxZ = value;
  48400. this.forceProjectionMatrixCompute();
  48401. },
  48402. enumerable: true,
  48403. configurable: true
  48404. });
  48405. /**
  48406. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48407. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48408. */
  48409. ShadowLight.prototype.computeTransformedInformation = function () {
  48410. if (this.parent && this.parent.getWorldMatrix) {
  48411. if (!this.transformedPosition) {
  48412. this.transformedPosition = BABYLON.Vector3.Zero();
  48413. }
  48414. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48415. // In case the direction is present.
  48416. if (this.direction) {
  48417. if (!this.transformedDirection) {
  48418. this.transformedDirection = BABYLON.Vector3.Zero();
  48419. }
  48420. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48421. }
  48422. return true;
  48423. }
  48424. return false;
  48425. };
  48426. /**
  48427. * Return the depth scale used for the shadow map.
  48428. * @returns the depth scale.
  48429. */
  48430. ShadowLight.prototype.getDepthScale = function () {
  48431. return 50.0;
  48432. };
  48433. /**
  48434. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48435. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48436. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48437. */
  48438. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48439. return this.transformedDirection ? this.transformedDirection : this.direction;
  48440. };
  48441. /**
  48442. * Returns the ShadowLight absolute position in the World.
  48443. * @returns the position vector in world space
  48444. */
  48445. ShadowLight.prototype.getAbsolutePosition = function () {
  48446. return this.transformedPosition ? this.transformedPosition : this.position;
  48447. };
  48448. /**
  48449. * Sets the ShadowLight direction toward the passed target.
  48450. * @param target The point tot target in local space
  48451. * @returns the updated ShadowLight direction
  48452. */
  48453. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48454. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48455. return this.direction;
  48456. };
  48457. /**
  48458. * Returns the light rotation in euler definition.
  48459. * @returns the x y z rotation in local space.
  48460. */
  48461. ShadowLight.prototype.getRotation = function () {
  48462. this.direction.normalize();
  48463. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48464. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48465. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48466. };
  48467. /**
  48468. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48469. * @returns true if a cube texture needs to be use
  48470. */
  48471. ShadowLight.prototype.needCube = function () {
  48472. return false;
  48473. };
  48474. /**
  48475. * Detects if the projection matrix requires to be recomputed this frame.
  48476. * @returns true if it requires to be recomputed otherwise, false.
  48477. */
  48478. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48479. return this._needProjectionMatrixCompute;
  48480. };
  48481. /**
  48482. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48483. */
  48484. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48485. this._needProjectionMatrixCompute = true;
  48486. };
  48487. /**
  48488. * Get the world matrix of the sahdow lights.
  48489. * @hidden Internal Use Only
  48490. */
  48491. ShadowLight.prototype._getWorldMatrix = function () {
  48492. if (!this._worldMatrix) {
  48493. this._worldMatrix = BABYLON.Matrix.Identity();
  48494. }
  48495. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48496. return this._worldMatrix;
  48497. };
  48498. /**
  48499. * Gets the minZ used for shadow according to both the scene and the light.
  48500. * @param activeCamera The camera we are returning the min for
  48501. * @returns the depth min z
  48502. */
  48503. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48504. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48505. };
  48506. /**
  48507. * Gets the maxZ used for shadow according to both the scene and the light.
  48508. * @param activeCamera The camera we are returning the max for
  48509. * @returns the depth max z
  48510. */
  48511. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48512. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48513. };
  48514. /**
  48515. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48516. * @param matrix The materix to updated with the projection information
  48517. * @param viewMatrix The transform matrix of the light
  48518. * @param renderList The list of mesh to render in the map
  48519. * @returns The current light
  48520. */
  48521. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48522. if (this.customProjectionMatrixBuilder) {
  48523. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48524. }
  48525. else {
  48526. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48527. }
  48528. return this;
  48529. };
  48530. __decorate([
  48531. BABYLON.serializeAsVector3()
  48532. ], ShadowLight.prototype, "position", null);
  48533. __decorate([
  48534. BABYLON.serializeAsVector3()
  48535. ], ShadowLight.prototype, "direction", null);
  48536. __decorate([
  48537. BABYLON.serialize()
  48538. ], ShadowLight.prototype, "shadowMinZ", null);
  48539. __decorate([
  48540. BABYLON.serialize()
  48541. ], ShadowLight.prototype, "shadowMaxZ", null);
  48542. return ShadowLight;
  48543. }(BABYLON.Light));
  48544. BABYLON.ShadowLight = ShadowLight;
  48545. })(BABYLON || (BABYLON = {}));
  48546. //# sourceMappingURL=babylon.shadowLight.js.map
  48547. var BABYLON;
  48548. (function (BABYLON) {
  48549. /**
  48550. * A point light is a light defined by an unique point in world space.
  48551. * The light is emitted in every direction from this point.
  48552. * A good example of a point light is a standard light bulb.
  48553. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48554. */
  48555. var PointLight = /** @class */ (function (_super) {
  48556. __extends(PointLight, _super);
  48557. /**
  48558. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48559. * A PointLight emits the light in every direction.
  48560. * It can cast shadows.
  48561. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48562. * ```javascript
  48563. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48564. * ```
  48565. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48566. * @param name The light friendly name
  48567. * @param position The position of the point light in the scene
  48568. * @param scene The scene the lights belongs to
  48569. */
  48570. function PointLight(name, position, scene) {
  48571. var _this = _super.call(this, name, scene) || this;
  48572. _this._shadowAngle = Math.PI / 2;
  48573. _this.position = position;
  48574. return _this;
  48575. }
  48576. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48577. /**
  48578. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48579. * This specifies what angle the shadow will use to be created.
  48580. *
  48581. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48582. */
  48583. get: function () {
  48584. return this._shadowAngle;
  48585. },
  48586. /**
  48587. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48588. * This specifies what angle the shadow will use to be created.
  48589. *
  48590. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48591. */
  48592. set: function (value) {
  48593. this._shadowAngle = value;
  48594. this.forceProjectionMatrixCompute();
  48595. },
  48596. enumerable: true,
  48597. configurable: true
  48598. });
  48599. Object.defineProperty(PointLight.prototype, "direction", {
  48600. /**
  48601. * Gets the direction if it has been set.
  48602. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48603. */
  48604. get: function () {
  48605. return this._direction;
  48606. },
  48607. /**
  48608. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48609. */
  48610. set: function (value) {
  48611. var previousNeedCube = this.needCube();
  48612. this._direction = value;
  48613. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48614. this._shadowGenerator.recreateShadowMap();
  48615. }
  48616. },
  48617. enumerable: true,
  48618. configurable: true
  48619. });
  48620. /**
  48621. * Returns the string "PointLight"
  48622. * @returns the class name
  48623. */
  48624. PointLight.prototype.getClassName = function () {
  48625. return "PointLight";
  48626. };
  48627. /**
  48628. * Returns the integer 0.
  48629. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48630. */
  48631. PointLight.prototype.getTypeID = function () {
  48632. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48633. };
  48634. /**
  48635. * Specifies wether or not the shadowmap should be a cube texture.
  48636. * @returns true if the shadowmap needs to be a cube texture.
  48637. */
  48638. PointLight.prototype.needCube = function () {
  48639. return !this.direction;
  48640. };
  48641. /**
  48642. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48643. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48644. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48645. */
  48646. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48647. if (this.direction) {
  48648. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48649. }
  48650. else {
  48651. switch (faceIndex) {
  48652. case 0:
  48653. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48654. case 1:
  48655. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48656. case 2:
  48657. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48658. case 3:
  48659. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48660. case 4:
  48661. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48662. case 5:
  48663. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48664. }
  48665. }
  48666. return BABYLON.Vector3.Zero();
  48667. };
  48668. /**
  48669. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48670. * - fov = PI / 2
  48671. * - aspect ratio : 1.0
  48672. * - z-near and far equal to the active camera minZ and maxZ.
  48673. * Returns the PointLight.
  48674. */
  48675. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48676. var activeCamera = this.getScene().activeCamera;
  48677. if (!activeCamera) {
  48678. return;
  48679. }
  48680. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48681. };
  48682. PointLight.prototype._buildUniformLayout = function () {
  48683. this._uniformBuffer.addUniform("vLightData", 4);
  48684. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48685. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48686. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48687. this._uniformBuffer.addUniform("depthValues", 2);
  48688. this._uniformBuffer.create();
  48689. };
  48690. /**
  48691. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48692. * @param effect The effect to update
  48693. * @param lightIndex The index of the light in the effect to update
  48694. * @returns The point light
  48695. */
  48696. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48697. if (this.computeTransformedInformation()) {
  48698. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48699. return this;
  48700. }
  48701. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48702. return this;
  48703. };
  48704. __decorate([
  48705. BABYLON.serialize()
  48706. ], PointLight.prototype, "shadowAngle", null);
  48707. return PointLight;
  48708. }(BABYLON.ShadowLight));
  48709. BABYLON.PointLight = PointLight;
  48710. })(BABYLON || (BABYLON = {}));
  48711. //# sourceMappingURL=babylon.pointLight.js.map
  48712. var BABYLON;
  48713. (function (BABYLON) {
  48714. /**
  48715. * A directional light is defined by a direction (what a surprise!).
  48716. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48717. * 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.
  48718. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48719. */
  48720. var DirectionalLight = /** @class */ (function (_super) {
  48721. __extends(DirectionalLight, _super);
  48722. /**
  48723. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48724. * The directional light is emitted from everywhere in the given direction.
  48725. * It can cast shawdows.
  48726. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48727. * @param name The friendly name of the light
  48728. * @param direction The direction of the light
  48729. * @param scene The scene the light belongs to
  48730. */
  48731. function DirectionalLight(name, direction, scene) {
  48732. var _this = _super.call(this, name, scene) || this;
  48733. _this._shadowFrustumSize = 0;
  48734. _this._shadowOrthoScale = 0.1;
  48735. /**
  48736. * Automatically compute the projection matrix to best fit (including all the casters)
  48737. * on each frame.
  48738. */
  48739. _this.autoUpdateExtends = true;
  48740. // Cache
  48741. _this._orthoLeft = Number.MAX_VALUE;
  48742. _this._orthoRight = Number.MIN_VALUE;
  48743. _this._orthoTop = Number.MIN_VALUE;
  48744. _this._orthoBottom = Number.MAX_VALUE;
  48745. _this.position = direction.scale(-1.0);
  48746. _this.direction = direction;
  48747. return _this;
  48748. }
  48749. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48750. /**
  48751. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48752. */
  48753. get: function () {
  48754. return this._shadowFrustumSize;
  48755. },
  48756. /**
  48757. * Specifies a fix frustum size for the shadow generation.
  48758. */
  48759. set: function (value) {
  48760. this._shadowFrustumSize = value;
  48761. this.forceProjectionMatrixCompute();
  48762. },
  48763. enumerable: true,
  48764. configurable: true
  48765. });
  48766. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48767. /**
  48768. * Gets the shadow projection scale against the optimal computed one.
  48769. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48770. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48771. */
  48772. get: function () {
  48773. return this._shadowOrthoScale;
  48774. },
  48775. /**
  48776. * Sets the shadow projection scale against the optimal computed one.
  48777. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48778. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48779. */
  48780. set: function (value) {
  48781. this._shadowOrthoScale = value;
  48782. this.forceProjectionMatrixCompute();
  48783. },
  48784. enumerable: true,
  48785. configurable: true
  48786. });
  48787. /**
  48788. * Returns the string "DirectionalLight".
  48789. * @return The class name
  48790. */
  48791. DirectionalLight.prototype.getClassName = function () {
  48792. return "DirectionalLight";
  48793. };
  48794. /**
  48795. * Returns the integer 1.
  48796. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48797. */
  48798. DirectionalLight.prototype.getTypeID = function () {
  48799. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48800. };
  48801. /**
  48802. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48803. * Returns the DirectionalLight Shadow projection matrix.
  48804. */
  48805. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48806. if (this.shadowFrustumSize > 0) {
  48807. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48808. }
  48809. else {
  48810. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48811. }
  48812. };
  48813. /**
  48814. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48815. * Returns the DirectionalLight Shadow projection matrix.
  48816. */
  48817. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48818. var activeCamera = this.getScene().activeCamera;
  48819. if (!activeCamera) {
  48820. return;
  48821. }
  48822. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48823. };
  48824. /**
  48825. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48826. * Returns the DirectionalLight Shadow projection matrix.
  48827. */
  48828. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48829. var activeCamera = this.getScene().activeCamera;
  48830. if (!activeCamera) {
  48831. return;
  48832. }
  48833. // Check extends
  48834. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48835. var tempVector3 = BABYLON.Vector3.Zero();
  48836. this._orthoLeft = Number.MAX_VALUE;
  48837. this._orthoRight = Number.MIN_VALUE;
  48838. this._orthoTop = Number.MIN_VALUE;
  48839. this._orthoBottom = Number.MAX_VALUE;
  48840. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48841. var mesh = renderList[meshIndex];
  48842. if (!mesh) {
  48843. continue;
  48844. }
  48845. var boundingInfo = mesh.getBoundingInfo();
  48846. var boundingBox = boundingInfo.boundingBox;
  48847. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48848. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48849. if (tempVector3.x < this._orthoLeft)
  48850. this._orthoLeft = tempVector3.x;
  48851. if (tempVector3.y < this._orthoBottom)
  48852. this._orthoBottom = tempVector3.y;
  48853. if (tempVector3.x > this._orthoRight)
  48854. this._orthoRight = tempVector3.x;
  48855. if (tempVector3.y > this._orthoTop)
  48856. this._orthoTop = tempVector3.y;
  48857. }
  48858. }
  48859. }
  48860. var xOffset = this._orthoRight - this._orthoLeft;
  48861. var yOffset = this._orthoTop - this._orthoBottom;
  48862. 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);
  48863. };
  48864. DirectionalLight.prototype._buildUniformLayout = function () {
  48865. this._uniformBuffer.addUniform("vLightData", 4);
  48866. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48867. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48868. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48869. this._uniformBuffer.addUniform("depthValues", 2);
  48870. this._uniformBuffer.create();
  48871. };
  48872. /**
  48873. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48874. * @param effect The effect to update
  48875. * @param lightIndex The index of the light in the effect to update
  48876. * @returns The directional light
  48877. */
  48878. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48879. if (this.computeTransformedInformation()) {
  48880. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48881. return this;
  48882. }
  48883. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48884. return this;
  48885. };
  48886. /**
  48887. * Gets the minZ used for shadow according to both the scene and the light.
  48888. *
  48889. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48890. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48891. * @param activeCamera The camera we are returning the min for
  48892. * @returns the depth min z
  48893. */
  48894. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48895. return 1;
  48896. };
  48897. /**
  48898. * Gets the maxZ used for shadow according to both the scene and the light.
  48899. *
  48900. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48901. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48902. * @param activeCamera The camera we are returning the max for
  48903. * @returns the depth max z
  48904. */
  48905. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48906. return 1;
  48907. };
  48908. __decorate([
  48909. BABYLON.serialize()
  48910. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48911. __decorate([
  48912. BABYLON.serialize()
  48913. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48914. __decorate([
  48915. BABYLON.serialize()
  48916. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48917. return DirectionalLight;
  48918. }(BABYLON.ShadowLight));
  48919. BABYLON.DirectionalLight = DirectionalLight;
  48920. })(BABYLON || (BABYLON = {}));
  48921. //# sourceMappingURL=babylon.directionalLight.js.map
  48922. var BABYLON;
  48923. (function (BABYLON) {
  48924. /**
  48925. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48926. * These values define a cone of light starting from the position, emitting toward the direction.
  48927. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48928. * and the exponent defines the speed of the decay of the light with distance (reach).
  48929. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48930. */
  48931. var SpotLight = /** @class */ (function (_super) {
  48932. __extends(SpotLight, _super);
  48933. /**
  48934. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48935. * It can cast shadows.
  48936. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48937. * @param name The light friendly name
  48938. * @param position The position of the spot light in the scene
  48939. * @param direction The direction of the light in the scene
  48940. * @param angle The cone angle of the light in Radians
  48941. * @param exponent The light decay speed with the distance from the emission spot
  48942. * @param scene The scene the lights belongs to
  48943. */
  48944. function SpotLight(name, position, direction, angle, exponent, scene) {
  48945. var _this = _super.call(this, name, scene) || this;
  48946. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48947. _this._projectionTextureLightNear = 1e-6;
  48948. _this._projectionTextureLightFar = 1000.0;
  48949. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48950. _this._projectionTextureViewLightDirty = true;
  48951. _this._projectionTextureProjectionLightDirty = true;
  48952. _this._projectionTextureDirty = true;
  48953. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48954. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48955. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48956. _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);
  48957. _this.position = position;
  48958. _this.direction = direction;
  48959. _this.angle = angle;
  48960. _this.exponent = exponent;
  48961. return _this;
  48962. }
  48963. Object.defineProperty(SpotLight.prototype, "angle", {
  48964. /**
  48965. * Gets the cone angle of the spot light in Radians.
  48966. */
  48967. get: function () {
  48968. return this._angle;
  48969. },
  48970. /**
  48971. * Sets the cone angle of the spot light in Radians.
  48972. */
  48973. set: function (value) {
  48974. this._angle = value;
  48975. this._projectionTextureProjectionLightDirty = true;
  48976. this.forceProjectionMatrixCompute();
  48977. },
  48978. enumerable: true,
  48979. configurable: true
  48980. });
  48981. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48982. /**
  48983. * Allows scaling the angle of the light for shadow generation only.
  48984. */
  48985. get: function () {
  48986. return this._shadowAngleScale;
  48987. },
  48988. /**
  48989. * Allows scaling the angle of the light for shadow generation only.
  48990. */
  48991. set: function (value) {
  48992. this._shadowAngleScale = value;
  48993. this.forceProjectionMatrixCompute();
  48994. },
  48995. enumerable: true,
  48996. configurable: true
  48997. });
  48998. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48999. /**
  49000. * Allows reading the projecton texture
  49001. */
  49002. get: function () {
  49003. return this._projectionTextureMatrix;
  49004. },
  49005. enumerable: true,
  49006. configurable: true
  49007. });
  49008. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49009. /**
  49010. * Gets the near clip of the Spotlight for texture projection.
  49011. */
  49012. get: function () {
  49013. return this._projectionTextureLightNear;
  49014. },
  49015. /**
  49016. * Sets the near clip of the Spotlight for texture projection.
  49017. */
  49018. set: function (value) {
  49019. this._projectionTextureLightNear = value;
  49020. this._projectionTextureProjectionLightDirty = true;
  49021. },
  49022. enumerable: true,
  49023. configurable: true
  49024. });
  49025. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49026. /**
  49027. * Gets the far clip of the Spotlight for texture projection.
  49028. */
  49029. get: function () {
  49030. return this._projectionTextureLightFar;
  49031. },
  49032. /**
  49033. * Sets the far clip of the Spotlight for texture projection.
  49034. */
  49035. set: function (value) {
  49036. this._projectionTextureLightFar = value;
  49037. this._projectionTextureProjectionLightDirty = true;
  49038. },
  49039. enumerable: true,
  49040. configurable: true
  49041. });
  49042. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49043. /**
  49044. * Gets the Up vector of the Spotlight for texture projection.
  49045. */
  49046. get: function () {
  49047. return this._projectionTextureUpDirection;
  49048. },
  49049. /**
  49050. * Sets the Up vector of the Spotlight for texture projection.
  49051. */
  49052. set: function (value) {
  49053. this._projectionTextureUpDirection = value;
  49054. this._projectionTextureProjectionLightDirty = true;
  49055. },
  49056. enumerable: true,
  49057. configurable: true
  49058. });
  49059. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49060. /**
  49061. * Gets the projection texture of the light.
  49062. */
  49063. get: function () {
  49064. return this._projectionTexture;
  49065. },
  49066. /**
  49067. * Sets the projection texture of the light.
  49068. */
  49069. set: function (value) {
  49070. this._projectionTexture = value;
  49071. this._projectionTextureDirty = true;
  49072. },
  49073. enumerable: true,
  49074. configurable: true
  49075. });
  49076. /**
  49077. * Returns the string "SpotLight".
  49078. * @returns the class name
  49079. */
  49080. SpotLight.prototype.getClassName = function () {
  49081. return "SpotLight";
  49082. };
  49083. /**
  49084. * Returns the integer 2.
  49085. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49086. */
  49087. SpotLight.prototype.getTypeID = function () {
  49088. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49089. };
  49090. /**
  49091. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49092. */
  49093. SpotLight.prototype._setDirection = function (value) {
  49094. _super.prototype._setDirection.call(this, value);
  49095. this._projectionTextureViewLightDirty = true;
  49096. };
  49097. /**
  49098. * Overrides the position setter to recompute the projection texture view light Matrix.
  49099. */
  49100. SpotLight.prototype._setPosition = function (value) {
  49101. _super.prototype._setPosition.call(this, value);
  49102. this._projectionTextureViewLightDirty = true;
  49103. };
  49104. /**
  49105. * 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.
  49106. * Returns the SpotLight.
  49107. */
  49108. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49109. var activeCamera = this.getScene().activeCamera;
  49110. if (!activeCamera) {
  49111. return;
  49112. }
  49113. this._shadowAngleScale = this._shadowAngleScale || 1;
  49114. var angle = this._shadowAngleScale * this._angle;
  49115. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49116. };
  49117. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49118. this._projectionTextureViewLightDirty = false;
  49119. this._projectionTextureDirty = true;
  49120. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49121. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49122. };
  49123. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49124. this._projectionTextureProjectionLightDirty = false;
  49125. this._projectionTextureDirty = true;
  49126. var light_far = this.projectionTextureLightFar;
  49127. var light_near = this.projectionTextureLightNear;
  49128. var P = light_far / (light_far - light_near);
  49129. var Q = -P * light_near;
  49130. var S = 1.0 / Math.tan(this._angle / 2.0);
  49131. var A = 1.0;
  49132. 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);
  49133. };
  49134. /**
  49135. * Main function for light texture projection matrix computing.
  49136. */
  49137. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49138. this._projectionTextureDirty = false;
  49139. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49140. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49141. };
  49142. SpotLight.prototype._buildUniformLayout = function () {
  49143. this._uniformBuffer.addUniform("vLightData", 4);
  49144. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49145. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49146. this._uniformBuffer.addUniform("vLightDirection", 3);
  49147. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49148. this._uniformBuffer.addUniform("depthValues", 2);
  49149. this._uniformBuffer.create();
  49150. };
  49151. /**
  49152. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49153. * @param effect The effect to update
  49154. * @param lightIndex The index of the light in the effect to update
  49155. * @returns The spot light
  49156. */
  49157. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49158. var normalizeDirection;
  49159. if (this.computeTransformedInformation()) {
  49160. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49161. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49162. }
  49163. else {
  49164. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49165. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49166. }
  49167. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49168. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49169. if (this._projectionTextureViewLightDirty) {
  49170. this._computeProjectionTextureViewLightMatrix();
  49171. }
  49172. if (this._projectionTextureProjectionLightDirty) {
  49173. this._computeProjectionTextureProjectionLightMatrix();
  49174. }
  49175. if (this._projectionTextureDirty) {
  49176. this._computeProjectionTextureMatrix();
  49177. }
  49178. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49179. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49180. }
  49181. return this;
  49182. };
  49183. /**
  49184. * Disposes the light and the associated resources.
  49185. */
  49186. SpotLight.prototype.dispose = function () {
  49187. _super.prototype.dispose.call(this);
  49188. if (this._projectionTexture) {
  49189. this._projectionTexture.dispose();
  49190. }
  49191. };
  49192. __decorate([
  49193. BABYLON.serialize()
  49194. ], SpotLight.prototype, "angle", null);
  49195. __decorate([
  49196. BABYLON.serialize()
  49197. ], SpotLight.prototype, "shadowAngleScale", null);
  49198. __decorate([
  49199. BABYLON.serialize()
  49200. ], SpotLight.prototype, "exponent", void 0);
  49201. __decorate([
  49202. BABYLON.serialize()
  49203. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49204. __decorate([
  49205. BABYLON.serialize()
  49206. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49207. __decorate([
  49208. BABYLON.serialize()
  49209. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49210. __decorate([
  49211. BABYLON.serializeAsTexture("projectedLightTexture")
  49212. ], SpotLight.prototype, "_projectionTexture", void 0);
  49213. return SpotLight;
  49214. }(BABYLON.ShadowLight));
  49215. BABYLON.SpotLight = SpotLight;
  49216. })(BABYLON || (BABYLON = {}));
  49217. //# sourceMappingURL=babylon.spotLight.js.map
  49218. var BABYLON;
  49219. (function (BABYLON) {
  49220. /**
  49221. * Class used to override all child animations of a given target
  49222. */
  49223. var AnimationPropertiesOverride = /** @class */ (function () {
  49224. function AnimationPropertiesOverride() {
  49225. /**
  49226. * Gets or sets a value indicating if animation blending must be used
  49227. */
  49228. this.enableBlending = false;
  49229. /**
  49230. * Gets or sets the blending speed to use when enableBlending is true
  49231. */
  49232. this.blendingSpeed = 0.01;
  49233. /**
  49234. * Gets or sets the default loop mode to use
  49235. */
  49236. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49237. }
  49238. return AnimationPropertiesOverride;
  49239. }());
  49240. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49241. })(BABYLON || (BABYLON = {}));
  49242. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49243. var BABYLON;
  49244. (function (BABYLON) {
  49245. /**
  49246. * Represents the range of an animation
  49247. */
  49248. var AnimationRange = /** @class */ (function () {
  49249. /**
  49250. * Initializes the range of an animation
  49251. * @param name The name of the animation range
  49252. * @param from The starting frame of the animation
  49253. * @param to The ending frame of the animation
  49254. */
  49255. function AnimationRange(
  49256. /**The name of the animation range**/
  49257. name,
  49258. /**The starting frame of the animation */
  49259. from,
  49260. /**The ending frame of the animation*/
  49261. to) {
  49262. this.name = name;
  49263. this.from = from;
  49264. this.to = to;
  49265. }
  49266. /**
  49267. * Makes a copy of the animation range
  49268. * @returns A copy of the animation range
  49269. */
  49270. AnimationRange.prototype.clone = function () {
  49271. return new AnimationRange(this.name, this.from, this.to);
  49272. };
  49273. return AnimationRange;
  49274. }());
  49275. BABYLON.AnimationRange = AnimationRange;
  49276. /**
  49277. * Composed of a frame, and an action function
  49278. */
  49279. var AnimationEvent = /** @class */ (function () {
  49280. /**
  49281. * Initializes the animation event
  49282. * @param frame The frame for which the event is triggered
  49283. * @param action The event to perform when triggered
  49284. * @param onlyOnce Specifies if the event should be triggered only once
  49285. */
  49286. function AnimationEvent(
  49287. /** The frame for which the event is triggered **/
  49288. frame,
  49289. /** The event to perform when triggered **/
  49290. action,
  49291. /** Specifies if the event should be triggered only once**/
  49292. onlyOnce) {
  49293. this.frame = frame;
  49294. this.action = action;
  49295. this.onlyOnce = onlyOnce;
  49296. /**
  49297. * Specifies if the animation event is done
  49298. */
  49299. this.isDone = false;
  49300. }
  49301. /** @hidden */
  49302. AnimationEvent.prototype._clone = function () {
  49303. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49304. };
  49305. return AnimationEvent;
  49306. }());
  49307. BABYLON.AnimationEvent = AnimationEvent;
  49308. /**
  49309. * A cursor which tracks a point on a path
  49310. */
  49311. var PathCursor = /** @class */ (function () {
  49312. /**
  49313. * Initializes the path cursor
  49314. * @param path The path to track
  49315. */
  49316. function PathCursor(path) {
  49317. this.path = path;
  49318. /**
  49319. * Stores path cursor callbacks for when an onchange event is triggered
  49320. */
  49321. this._onchange = new Array();
  49322. /**
  49323. * The value of the path cursor
  49324. */
  49325. this.value = 0;
  49326. /**
  49327. * The animation array of the path cursor
  49328. */
  49329. this.animations = new Array();
  49330. }
  49331. /**
  49332. * Gets the cursor point on the path
  49333. * @returns A point on the path cursor at the cursor location
  49334. */
  49335. PathCursor.prototype.getPoint = function () {
  49336. var point = this.path.getPointAtLengthPosition(this.value);
  49337. return new BABYLON.Vector3(point.x, 0, point.y);
  49338. };
  49339. /**
  49340. * Moves the cursor ahead by the step amount
  49341. * @param step The amount to move the cursor forward
  49342. * @returns This path cursor
  49343. */
  49344. PathCursor.prototype.moveAhead = function (step) {
  49345. if (step === void 0) { step = 0.002; }
  49346. this.move(step);
  49347. return this;
  49348. };
  49349. /**
  49350. * Moves the cursor behind by the step amount
  49351. * @param step The amount to move the cursor back
  49352. * @returns This path cursor
  49353. */
  49354. PathCursor.prototype.moveBack = function (step) {
  49355. if (step === void 0) { step = 0.002; }
  49356. this.move(-step);
  49357. return this;
  49358. };
  49359. /**
  49360. * Moves the cursor by the step amount
  49361. * If the step amount is greater than one, an exception is thrown
  49362. * @param step The amount to move the cursor
  49363. * @returns This path cursor
  49364. */
  49365. PathCursor.prototype.move = function (step) {
  49366. if (Math.abs(step) > 1) {
  49367. throw "step size should be less than 1.";
  49368. }
  49369. this.value += step;
  49370. this.ensureLimits();
  49371. this.raiseOnChange();
  49372. return this;
  49373. };
  49374. /**
  49375. * Ensures that the value is limited between zero and one
  49376. * @returns This path cursor
  49377. */
  49378. PathCursor.prototype.ensureLimits = function () {
  49379. while (this.value > 1) {
  49380. this.value -= 1;
  49381. }
  49382. while (this.value < 0) {
  49383. this.value += 1;
  49384. }
  49385. return this;
  49386. };
  49387. /**
  49388. * Runs onchange callbacks on change (used by the animation engine)
  49389. * @returns This path cursor
  49390. */
  49391. PathCursor.prototype.raiseOnChange = function () {
  49392. var _this = this;
  49393. this._onchange.forEach(function (f) { return f(_this); });
  49394. return this;
  49395. };
  49396. /**
  49397. * Executes a function on change
  49398. * @param f A path cursor onchange callback
  49399. * @returns This path cursor
  49400. */
  49401. PathCursor.prototype.onchange = function (f) {
  49402. this._onchange.push(f);
  49403. return this;
  49404. };
  49405. return PathCursor;
  49406. }());
  49407. BABYLON.PathCursor = PathCursor;
  49408. /**
  49409. * Enum for the animation key frame interpolation type
  49410. */
  49411. var AnimationKeyInterpolation;
  49412. (function (AnimationKeyInterpolation) {
  49413. /**
  49414. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49415. */
  49416. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49417. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49418. /**
  49419. * Class used to store any kind of animation
  49420. */
  49421. var Animation = /** @class */ (function () {
  49422. /**
  49423. * Initializes the animation
  49424. * @param name Name of the animation
  49425. * @param targetProperty Property to animate
  49426. * @param framePerSecond The frames per second of the animation
  49427. * @param dataType The data type of the animation
  49428. * @param loopMode The loop mode of the animation
  49429. * @param enableBlendings Specifies if blending should be enabled
  49430. */
  49431. function Animation(
  49432. /**Name of the animation */
  49433. name,
  49434. /**Property to animate */
  49435. targetProperty,
  49436. /**The frames per second of the animation */
  49437. framePerSecond,
  49438. /**The data type of the animation */
  49439. dataType,
  49440. /**The loop mode of the animation */
  49441. loopMode,
  49442. /**Specifies if blending should be enabled */
  49443. enableBlending) {
  49444. this.name = name;
  49445. this.targetProperty = targetProperty;
  49446. this.framePerSecond = framePerSecond;
  49447. this.dataType = dataType;
  49448. this.loopMode = loopMode;
  49449. this.enableBlending = enableBlending;
  49450. /**
  49451. * @hidden Internal use only
  49452. */
  49453. this._runtimeAnimations = new Array();
  49454. /**
  49455. * The set of event that will be linked to this animation
  49456. */
  49457. this._events = new Array();
  49458. /**
  49459. * Stores the blending speed of the animation
  49460. */
  49461. this.blendingSpeed = 0.01;
  49462. /**
  49463. * Stores the animation ranges for the animation
  49464. */
  49465. this._ranges = {};
  49466. this.targetPropertyPath = targetProperty.split(".");
  49467. this.dataType = dataType;
  49468. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49469. }
  49470. /**
  49471. * @hidden Internal use
  49472. */
  49473. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49474. var dataType = undefined;
  49475. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49476. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49477. }
  49478. else if (from instanceof BABYLON.Quaternion) {
  49479. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49480. }
  49481. else if (from instanceof BABYLON.Vector3) {
  49482. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49483. }
  49484. else if (from instanceof BABYLON.Vector2) {
  49485. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49486. }
  49487. else if (from instanceof BABYLON.Color3) {
  49488. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49489. }
  49490. else if (from instanceof BABYLON.Size) {
  49491. dataType = Animation.ANIMATIONTYPE_SIZE;
  49492. }
  49493. if (dataType == undefined) {
  49494. return null;
  49495. }
  49496. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49497. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49498. animation.setKeys(keys);
  49499. if (easingFunction !== undefined) {
  49500. animation.setEasingFunction(easingFunction);
  49501. }
  49502. return animation;
  49503. };
  49504. /**
  49505. * Sets up an animation
  49506. * @param property The property to animate
  49507. * @param animationType The animation type to apply
  49508. * @param framePerSecond The frames per second of the animation
  49509. * @param easingFunction The easing function used in the animation
  49510. * @returns The created animation
  49511. */
  49512. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49513. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49514. animation.setEasingFunction(easingFunction);
  49515. return animation;
  49516. };
  49517. /**
  49518. * Create and start an animation on a node
  49519. * @param name defines the name of the global animation that will be run on all nodes
  49520. * @param node defines the root node where the animation will take place
  49521. * @param targetProperty defines property to animate
  49522. * @param framePerSecond defines the number of frame per second yo use
  49523. * @param totalFrame defines the number of frames in total
  49524. * @param from defines the initial value
  49525. * @param to defines the final value
  49526. * @param loopMode defines which loop mode you want to use (off by default)
  49527. * @param easingFunction defines the easing function to use (linear by default)
  49528. * @param onAnimationEnd defines the callback to call when animation end
  49529. * @returns the animatable created for this animation
  49530. */
  49531. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49532. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49533. if (!animation) {
  49534. return null;
  49535. }
  49536. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49537. };
  49538. /**
  49539. * Create and start an animation on a node and its descendants
  49540. * @param name defines the name of the global animation that will be run on all nodes
  49541. * @param node defines the root node where the animation will take place
  49542. * @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
  49543. * @param targetProperty defines property to animate
  49544. * @param framePerSecond defines the number of frame per second to use
  49545. * @param totalFrame defines the number of frames in total
  49546. * @param from defines the initial value
  49547. * @param to defines the final value
  49548. * @param loopMode defines which loop mode you want to use (off by default)
  49549. * @param easingFunction defines the easing function to use (linear by default)
  49550. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49551. * @returns the list of animatables created for all nodes
  49552. * @example https://www.babylonjs-playground.com/#MH0VLI
  49553. */
  49554. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49555. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49556. if (!animation) {
  49557. return null;
  49558. }
  49559. var scene = node.getScene();
  49560. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49561. };
  49562. /**
  49563. * Creates a new animation, merges it with the existing animations and starts it
  49564. * @param name Name of the animation
  49565. * @param node Node which contains the scene that begins the animations
  49566. * @param targetProperty Specifies which property to animate
  49567. * @param framePerSecond The frames per second of the animation
  49568. * @param totalFrame The total number of frames
  49569. * @param from The frame at the beginning of the animation
  49570. * @param to The frame at the end of the animation
  49571. * @param loopMode Specifies the loop mode of the animation
  49572. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49573. * @param onAnimationEnd Callback to run once the animation is complete
  49574. * @returns Nullable animation
  49575. */
  49576. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49577. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49578. if (!animation) {
  49579. return null;
  49580. }
  49581. node.animations.push(animation);
  49582. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49583. };
  49584. /**
  49585. * Transition property of an host to the target Value
  49586. * @param property The property to transition
  49587. * @param targetValue The target Value of the property
  49588. * @param host The object where the property to animate belongs
  49589. * @param scene Scene used to run the animation
  49590. * @param frameRate Framerate (in frame/s) to use
  49591. * @param transition The transition type we want to use
  49592. * @param duration The duration of the animation, in milliseconds
  49593. * @param onAnimationEnd Callback trigger at the end of the animation
  49594. * @returns Nullable animation
  49595. */
  49596. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49597. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49598. if (duration <= 0) {
  49599. host[property] = targetValue;
  49600. if (onAnimationEnd) {
  49601. onAnimationEnd();
  49602. }
  49603. return null;
  49604. }
  49605. var endFrame = frameRate * (duration / 1000);
  49606. transition.setKeys([{
  49607. frame: 0,
  49608. value: host[property].clone ? host[property].clone() : host[property]
  49609. },
  49610. {
  49611. frame: endFrame,
  49612. value: targetValue
  49613. }]);
  49614. if (!host.animations) {
  49615. host.animations = [];
  49616. }
  49617. host.animations.push(transition);
  49618. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49619. animation.onAnimationEnd = onAnimationEnd;
  49620. return animation;
  49621. };
  49622. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49623. /**
  49624. * Return the array of runtime animations currently using this animation
  49625. */
  49626. get: function () {
  49627. return this._runtimeAnimations;
  49628. },
  49629. enumerable: true,
  49630. configurable: true
  49631. });
  49632. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49633. /**
  49634. * Specifies if any of the runtime animations are currently running
  49635. */
  49636. get: function () {
  49637. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49638. var runtimeAnimation = _a[_i];
  49639. if (!runtimeAnimation.isStopped) {
  49640. return true;
  49641. }
  49642. }
  49643. return false;
  49644. },
  49645. enumerable: true,
  49646. configurable: true
  49647. });
  49648. // Methods
  49649. /**
  49650. * Converts the animation to a string
  49651. * @param fullDetails support for multiple levels of logging within scene loading
  49652. * @returns String form of the animation
  49653. */
  49654. Animation.prototype.toString = function (fullDetails) {
  49655. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49656. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49657. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49658. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49659. if (fullDetails) {
  49660. ret += ", Ranges: {";
  49661. var first = true;
  49662. for (var name in this._ranges) {
  49663. if (first) {
  49664. ret += ", ";
  49665. first = false;
  49666. }
  49667. ret += name;
  49668. }
  49669. ret += "}";
  49670. }
  49671. return ret;
  49672. };
  49673. /**
  49674. * Add an event to this animation
  49675. * @param event Event to add
  49676. */
  49677. Animation.prototype.addEvent = function (event) {
  49678. this._events.push(event);
  49679. };
  49680. /**
  49681. * Remove all events found at the given frame
  49682. * @param frame The frame to remove events from
  49683. */
  49684. Animation.prototype.removeEvents = function (frame) {
  49685. for (var index = 0; index < this._events.length; index++) {
  49686. if (this._events[index].frame === frame) {
  49687. this._events.splice(index, 1);
  49688. index--;
  49689. }
  49690. }
  49691. };
  49692. /**
  49693. * Retrieves all the events from the animation
  49694. * @returns Events from the animation
  49695. */
  49696. Animation.prototype.getEvents = function () {
  49697. return this._events;
  49698. };
  49699. /**
  49700. * Creates an animation range
  49701. * @param name Name of the animation range
  49702. * @param from Starting frame of the animation range
  49703. * @param to Ending frame of the animation
  49704. */
  49705. Animation.prototype.createRange = function (name, from, to) {
  49706. // check name not already in use; could happen for bones after serialized
  49707. if (!this._ranges[name]) {
  49708. this._ranges[name] = new AnimationRange(name, from, to);
  49709. }
  49710. };
  49711. /**
  49712. * Deletes an animation range by name
  49713. * @param name Name of the animation range to delete
  49714. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49715. */
  49716. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49717. if (deleteFrames === void 0) { deleteFrames = true; }
  49718. var range = this._ranges[name];
  49719. if (!range) {
  49720. return;
  49721. }
  49722. if (deleteFrames) {
  49723. var from = range.from;
  49724. var to = range.to;
  49725. // this loop MUST go high to low for multiple splices to work
  49726. for (var key = this._keys.length - 1; key >= 0; key--) {
  49727. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49728. this._keys.splice(key, 1);
  49729. }
  49730. }
  49731. }
  49732. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49733. };
  49734. /**
  49735. * Gets the animation range by name, or null if not defined
  49736. * @param name Name of the animation range
  49737. * @returns Nullable animation range
  49738. */
  49739. Animation.prototype.getRange = function (name) {
  49740. return this._ranges[name];
  49741. };
  49742. /**
  49743. * Gets the key frames from the animation
  49744. * @returns The key frames of the animation
  49745. */
  49746. Animation.prototype.getKeys = function () {
  49747. return this._keys;
  49748. };
  49749. /**
  49750. * Gets the highest frame rate of the animation
  49751. * @returns Highest frame rate of the animation
  49752. */
  49753. Animation.prototype.getHighestFrame = function () {
  49754. var ret = 0;
  49755. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49756. if (ret < this._keys[key].frame) {
  49757. ret = this._keys[key].frame;
  49758. }
  49759. }
  49760. return ret;
  49761. };
  49762. /**
  49763. * Gets the easing function of the animation
  49764. * @returns Easing function of the animation
  49765. */
  49766. Animation.prototype.getEasingFunction = function () {
  49767. return this._easingFunction;
  49768. };
  49769. /**
  49770. * Sets the easing function of the animation
  49771. * @param easingFunction A custom mathematical formula for animation
  49772. */
  49773. Animation.prototype.setEasingFunction = function (easingFunction) {
  49774. this._easingFunction = easingFunction;
  49775. };
  49776. /**
  49777. * Interpolates a scalar linearly
  49778. * @param startValue Start value of the animation curve
  49779. * @param endValue End value of the animation curve
  49780. * @param gradient Scalar amount to interpolate
  49781. * @returns Interpolated scalar value
  49782. */
  49783. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49784. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49785. };
  49786. /**
  49787. * Interpolates a scalar cubically
  49788. * @param startValue Start value of the animation curve
  49789. * @param outTangent End tangent of the animation
  49790. * @param endValue End value of the animation curve
  49791. * @param inTangent Start tangent of the animation curve
  49792. * @param gradient Scalar amount to interpolate
  49793. * @returns Interpolated scalar value
  49794. */
  49795. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49796. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49797. };
  49798. /**
  49799. * Interpolates a quaternion using a spherical linear interpolation
  49800. * @param startValue Start value of the animation curve
  49801. * @param endValue End value of the animation curve
  49802. * @param gradient Scalar amount to interpolate
  49803. * @returns Interpolated quaternion value
  49804. */
  49805. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49806. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49807. };
  49808. /**
  49809. * Interpolates a quaternion cubically
  49810. * @param startValue Start value of the animation curve
  49811. * @param outTangent End tangent of the animation curve
  49812. * @param endValue End value of the animation curve
  49813. * @param inTangent Start tangent of the animation curve
  49814. * @param gradient Scalar amount to interpolate
  49815. * @returns Interpolated quaternion value
  49816. */
  49817. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49818. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49819. };
  49820. /**
  49821. * Interpolates a Vector3 linearl
  49822. * @param startValue Start value of the animation curve
  49823. * @param endValue End value of the animation curve
  49824. * @param gradient Scalar amount to interpolate
  49825. * @returns Interpolated scalar value
  49826. */
  49827. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49828. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49829. };
  49830. /**
  49831. * Interpolates a Vector3 cubically
  49832. * @param startValue Start value of the animation curve
  49833. * @param outTangent End tangent of the animation
  49834. * @param endValue End value of the animation curve
  49835. * @param inTangent Start tangent of the animation curve
  49836. * @param gradient Scalar amount to interpolate
  49837. * @returns InterpolatedVector3 value
  49838. */
  49839. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49840. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49841. };
  49842. /**
  49843. * Interpolates a Vector2 linearly
  49844. * @param startValue Start value of the animation curve
  49845. * @param endValue End value of the animation curve
  49846. * @param gradient Scalar amount to interpolate
  49847. * @returns Interpolated Vector2 value
  49848. */
  49849. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49850. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49851. };
  49852. /**
  49853. * Interpolates a Vector2 cubically
  49854. * @param startValue Start value of the animation curve
  49855. * @param outTangent End tangent of the animation
  49856. * @param endValue End value of the animation curve
  49857. * @param inTangent Start tangent of the animation curve
  49858. * @param gradient Scalar amount to interpolate
  49859. * @returns Interpolated Vector2 value
  49860. */
  49861. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49862. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49863. };
  49864. /**
  49865. * Interpolates a size linearly
  49866. * @param startValue Start value of the animation curve
  49867. * @param endValue End value of the animation curve
  49868. * @param gradient Scalar amount to interpolate
  49869. * @returns Interpolated Size value
  49870. */
  49871. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49872. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49873. };
  49874. /**
  49875. * Interpolates a Color3 linearly
  49876. * @param startValue Start value of the animation curve
  49877. * @param endValue End value of the animation curve
  49878. * @param gradient Scalar amount to interpolate
  49879. * @returns Interpolated Color3 value
  49880. */
  49881. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49882. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49883. };
  49884. /**
  49885. * @hidden Internal use only
  49886. */
  49887. Animation.prototype._getKeyValue = function (value) {
  49888. if (typeof value === "function") {
  49889. return value();
  49890. }
  49891. return value;
  49892. };
  49893. /**
  49894. * @hidden Internal use only
  49895. */
  49896. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49897. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49898. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49899. }
  49900. var keys = this.getKeys();
  49901. // Try to get a hash to find the right key
  49902. 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));
  49903. if (keys[startKeyIndex].frame >= currentFrame) {
  49904. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49905. startKeyIndex--;
  49906. }
  49907. }
  49908. for (var key = startKeyIndex; key < keys.length; key++) {
  49909. var endKey = keys[key + 1];
  49910. if (endKey.frame >= currentFrame) {
  49911. var startKey = keys[key];
  49912. var startValue = this._getKeyValue(startKey.value);
  49913. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49914. return startValue;
  49915. }
  49916. var endValue = this._getKeyValue(endKey.value);
  49917. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49918. var frameDelta = endKey.frame - startKey.frame;
  49919. // gradient : percent of currentFrame between the frame inf and the frame sup
  49920. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49921. // check for easingFunction and correction of gradient
  49922. var easingFunction = this.getEasingFunction();
  49923. if (easingFunction != null) {
  49924. gradient = easingFunction.ease(gradient);
  49925. }
  49926. switch (this.dataType) {
  49927. // Float
  49928. case Animation.ANIMATIONTYPE_FLOAT:
  49929. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49930. switch (loopMode) {
  49931. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49932. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49933. return floatValue;
  49934. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49935. return offsetValue * repeatCount + floatValue;
  49936. }
  49937. break;
  49938. // Quaternion
  49939. case Animation.ANIMATIONTYPE_QUATERNION:
  49940. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49941. switch (loopMode) {
  49942. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49943. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49944. return quatValue;
  49945. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49946. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49947. }
  49948. return quatValue;
  49949. // Vector3
  49950. case Animation.ANIMATIONTYPE_VECTOR3:
  49951. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49952. switch (loopMode) {
  49953. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49954. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49955. return vec3Value;
  49956. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49957. return vec3Value.add(offsetValue.scale(repeatCount));
  49958. }
  49959. // Vector2
  49960. case Animation.ANIMATIONTYPE_VECTOR2:
  49961. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49962. switch (loopMode) {
  49963. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49964. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49965. return vec2Value;
  49966. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49967. return vec2Value.add(offsetValue.scale(repeatCount));
  49968. }
  49969. // Size
  49970. case Animation.ANIMATIONTYPE_SIZE:
  49971. switch (loopMode) {
  49972. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49973. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49974. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49975. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49976. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49977. }
  49978. // Color3
  49979. case Animation.ANIMATIONTYPE_COLOR3:
  49980. switch (loopMode) {
  49981. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49982. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49983. return this.color3InterpolateFunction(startValue, endValue, gradient);
  49984. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49985. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49986. }
  49987. // Matrix
  49988. case Animation.ANIMATIONTYPE_MATRIX:
  49989. switch (loopMode) {
  49990. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49991. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49992. if (Animation.AllowMatricesInterpolation) {
  49993. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  49994. }
  49995. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49996. return startValue;
  49997. }
  49998. default:
  49999. break;
  50000. }
  50001. break;
  50002. }
  50003. }
  50004. return this._getKeyValue(keys[keys.length - 1].value);
  50005. };
  50006. /**
  50007. * Defines the function to use to interpolate matrices
  50008. * @param startValue defines the start matrix
  50009. * @param endValue defines the end matrix
  50010. * @param gradient defines the gradient between both matrices
  50011. * @param result defines an optional target matrix where to store the interpolation
  50012. * @returns the interpolated matrix
  50013. */
  50014. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50015. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50016. if (result) {
  50017. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50018. return result;
  50019. }
  50020. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50021. }
  50022. if (result) {
  50023. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50024. return result;
  50025. }
  50026. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50027. };
  50028. /**
  50029. * Makes a copy of the animation
  50030. * @returns Cloned animation
  50031. */
  50032. Animation.prototype.clone = function () {
  50033. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50034. clone.enableBlending = this.enableBlending;
  50035. clone.blendingSpeed = this.blendingSpeed;
  50036. if (this._keys) {
  50037. clone.setKeys(this._keys);
  50038. }
  50039. if (this._ranges) {
  50040. clone._ranges = {};
  50041. for (var name in this._ranges) {
  50042. var range = this._ranges[name];
  50043. if (!range) {
  50044. continue;
  50045. }
  50046. clone._ranges[name] = range.clone();
  50047. }
  50048. }
  50049. return clone;
  50050. };
  50051. /**
  50052. * Sets the key frames of the animation
  50053. * @param values The animation key frames to set
  50054. */
  50055. Animation.prototype.setKeys = function (values) {
  50056. this._keys = values.slice(0);
  50057. };
  50058. /**
  50059. * Serializes the animation to an object
  50060. * @returns Serialized object
  50061. */
  50062. Animation.prototype.serialize = function () {
  50063. var serializationObject = {};
  50064. serializationObject.name = this.name;
  50065. serializationObject.property = this.targetProperty;
  50066. serializationObject.framePerSecond = this.framePerSecond;
  50067. serializationObject.dataType = this.dataType;
  50068. serializationObject.loopBehavior = this.loopMode;
  50069. serializationObject.enableBlending = this.enableBlending;
  50070. serializationObject.blendingSpeed = this.blendingSpeed;
  50071. var dataType = this.dataType;
  50072. serializationObject.keys = [];
  50073. var keys = this.getKeys();
  50074. for (var index = 0; index < keys.length; index++) {
  50075. var animationKey = keys[index];
  50076. var key = {};
  50077. key.frame = animationKey.frame;
  50078. switch (dataType) {
  50079. case Animation.ANIMATIONTYPE_FLOAT:
  50080. key.values = [animationKey.value];
  50081. break;
  50082. case Animation.ANIMATIONTYPE_QUATERNION:
  50083. case Animation.ANIMATIONTYPE_MATRIX:
  50084. case Animation.ANIMATIONTYPE_VECTOR3:
  50085. case Animation.ANIMATIONTYPE_COLOR3:
  50086. key.values = animationKey.value.asArray();
  50087. break;
  50088. }
  50089. serializationObject.keys.push(key);
  50090. }
  50091. serializationObject.ranges = [];
  50092. for (var name in this._ranges) {
  50093. var source = this._ranges[name];
  50094. if (!source) {
  50095. continue;
  50096. }
  50097. var range = {};
  50098. range.name = name;
  50099. range.from = source.from;
  50100. range.to = source.to;
  50101. serializationObject.ranges.push(range);
  50102. }
  50103. return serializationObject;
  50104. };
  50105. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50106. /**
  50107. * Get the float animation type
  50108. */
  50109. get: function () {
  50110. return Animation._ANIMATIONTYPE_FLOAT;
  50111. },
  50112. enumerable: true,
  50113. configurable: true
  50114. });
  50115. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50116. /**
  50117. * Get the Vector3 animation type
  50118. */
  50119. get: function () {
  50120. return Animation._ANIMATIONTYPE_VECTOR3;
  50121. },
  50122. enumerable: true,
  50123. configurable: true
  50124. });
  50125. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50126. /**
  50127. * Get the Vectpr2 animation type
  50128. */
  50129. get: function () {
  50130. return Animation._ANIMATIONTYPE_VECTOR2;
  50131. },
  50132. enumerable: true,
  50133. configurable: true
  50134. });
  50135. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50136. /**
  50137. * Get the Size animation type
  50138. */
  50139. get: function () {
  50140. return Animation._ANIMATIONTYPE_SIZE;
  50141. },
  50142. enumerable: true,
  50143. configurable: true
  50144. });
  50145. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50146. /**
  50147. * Get the Quaternion animation type
  50148. */
  50149. get: function () {
  50150. return Animation._ANIMATIONTYPE_QUATERNION;
  50151. },
  50152. enumerable: true,
  50153. configurable: true
  50154. });
  50155. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50156. /**
  50157. * Get the Matrix animation type
  50158. */
  50159. get: function () {
  50160. return Animation._ANIMATIONTYPE_MATRIX;
  50161. },
  50162. enumerable: true,
  50163. configurable: true
  50164. });
  50165. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50166. /**
  50167. * Get the Color3 animation type
  50168. */
  50169. get: function () {
  50170. return Animation._ANIMATIONTYPE_COLOR3;
  50171. },
  50172. enumerable: true,
  50173. configurable: true
  50174. });
  50175. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50176. /**
  50177. * Get the Relative Loop Mode
  50178. */
  50179. get: function () {
  50180. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50181. },
  50182. enumerable: true,
  50183. configurable: true
  50184. });
  50185. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50186. /**
  50187. * Get the Cycle Loop Mode
  50188. */
  50189. get: function () {
  50190. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50191. },
  50192. enumerable: true,
  50193. configurable: true
  50194. });
  50195. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50196. /**
  50197. * Get the Constant Loop Mode
  50198. */
  50199. get: function () {
  50200. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50201. },
  50202. enumerable: true,
  50203. configurable: true
  50204. });
  50205. /** @hidden */
  50206. Animation._UniversalLerp = function (left, right, amount) {
  50207. var constructor = left.constructor;
  50208. if (constructor.Lerp) { // Lerp supported
  50209. return constructor.Lerp(left, right, amount);
  50210. }
  50211. else if (constructor.Slerp) { // Slerp supported
  50212. return constructor.Slerp(left, right, amount);
  50213. }
  50214. else if (left.toFixed) { // Number
  50215. return left * (1.0 - amount) + amount * right;
  50216. }
  50217. else { // Blending not supported
  50218. return right;
  50219. }
  50220. };
  50221. /**
  50222. * Parses an animation object and creates an animation
  50223. * @param parsedAnimation Parsed animation object
  50224. * @returns Animation object
  50225. */
  50226. Animation.Parse = function (parsedAnimation) {
  50227. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50228. var dataType = parsedAnimation.dataType;
  50229. var keys = [];
  50230. var data;
  50231. var index;
  50232. if (parsedAnimation.enableBlending) {
  50233. animation.enableBlending = parsedAnimation.enableBlending;
  50234. }
  50235. if (parsedAnimation.blendingSpeed) {
  50236. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50237. }
  50238. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50239. var key = parsedAnimation.keys[index];
  50240. var inTangent;
  50241. var outTangent;
  50242. switch (dataType) {
  50243. case Animation.ANIMATIONTYPE_FLOAT:
  50244. data = key.values[0];
  50245. if (key.values.length >= 1) {
  50246. inTangent = key.values[1];
  50247. }
  50248. if (key.values.length >= 2) {
  50249. outTangent = key.values[2];
  50250. }
  50251. break;
  50252. case Animation.ANIMATIONTYPE_QUATERNION:
  50253. data = BABYLON.Quaternion.FromArray(key.values);
  50254. if (key.values.length >= 8) {
  50255. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50256. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50257. inTangent = _inTangent;
  50258. }
  50259. }
  50260. if (key.values.length >= 12) {
  50261. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50262. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50263. outTangent = _outTangent;
  50264. }
  50265. }
  50266. break;
  50267. case Animation.ANIMATIONTYPE_MATRIX:
  50268. data = BABYLON.Matrix.FromArray(key.values);
  50269. break;
  50270. case Animation.ANIMATIONTYPE_COLOR3:
  50271. data = BABYLON.Color3.FromArray(key.values);
  50272. break;
  50273. case Animation.ANIMATIONTYPE_VECTOR3:
  50274. default:
  50275. data = BABYLON.Vector3.FromArray(key.values);
  50276. break;
  50277. }
  50278. var keyData = {};
  50279. keyData.frame = key.frame;
  50280. keyData.value = data;
  50281. if (inTangent != undefined) {
  50282. keyData.inTangent = inTangent;
  50283. }
  50284. if (outTangent != undefined) {
  50285. keyData.outTangent = outTangent;
  50286. }
  50287. keys.push(keyData);
  50288. }
  50289. animation.setKeys(keys);
  50290. if (parsedAnimation.ranges) {
  50291. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50292. data = parsedAnimation.ranges[index];
  50293. animation.createRange(data.name, data.from, data.to);
  50294. }
  50295. }
  50296. return animation;
  50297. };
  50298. /**
  50299. * Appends the serialized animations from the source animations
  50300. * @param source Source containing the animations
  50301. * @param destination Target to store the animations
  50302. */
  50303. Animation.AppendSerializedAnimations = function (source, destination) {
  50304. if (source.animations) {
  50305. destination.animations = [];
  50306. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50307. var animation = source.animations[animationIndex];
  50308. destination.animations.push(animation.serialize());
  50309. }
  50310. }
  50311. };
  50312. /**
  50313. * Use matrix interpolation instead of using direct key value when animating matrices
  50314. */
  50315. Animation.AllowMatricesInterpolation = false;
  50316. /**
  50317. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50318. */
  50319. Animation.AllowMatrixDecomposeForInterpolation = true;
  50320. // Statics
  50321. /**
  50322. * Float animation type
  50323. */
  50324. Animation._ANIMATIONTYPE_FLOAT = 0;
  50325. /**
  50326. * Vector3 animation type
  50327. */
  50328. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50329. /**
  50330. * Quaternion animation type
  50331. */
  50332. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50333. /**
  50334. * Matrix animation type
  50335. */
  50336. Animation._ANIMATIONTYPE_MATRIX = 3;
  50337. /**
  50338. * Color3 animation type
  50339. */
  50340. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50341. /**
  50342. * Vector2 animation type
  50343. */
  50344. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50345. /**
  50346. * Size animation type
  50347. */
  50348. Animation._ANIMATIONTYPE_SIZE = 6;
  50349. /**
  50350. * Relative Loop Mode
  50351. */
  50352. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50353. /**
  50354. * Cycle Loop Mode
  50355. */
  50356. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50357. /**
  50358. * Constant Loop Mode
  50359. */
  50360. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50361. return Animation;
  50362. }());
  50363. BABYLON.Animation = Animation;
  50364. })(BABYLON || (BABYLON = {}));
  50365. //# sourceMappingURL=babylon.animation.js.map
  50366. var BABYLON;
  50367. (function (BABYLON) {
  50368. /**
  50369. * This class defines the direct association between an animation and a target
  50370. */
  50371. var TargetedAnimation = /** @class */ (function () {
  50372. function TargetedAnimation() {
  50373. }
  50374. return TargetedAnimation;
  50375. }());
  50376. BABYLON.TargetedAnimation = TargetedAnimation;
  50377. /**
  50378. * Use this class to create coordinated animations on multiple targets
  50379. */
  50380. var AnimationGroup = /** @class */ (function () {
  50381. function AnimationGroup(name, scene) {
  50382. if (scene === void 0) { scene = null; }
  50383. this.name = name;
  50384. this._targetedAnimations = new Array();
  50385. this._animatables = new Array();
  50386. this._from = Number.MAX_VALUE;
  50387. this._to = -Number.MAX_VALUE;
  50388. this._speedRatio = 1;
  50389. this.onAnimationEndObservable = new BABYLON.Observable();
  50390. /**
  50391. * This observable will notify when all animations have ended.
  50392. */
  50393. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50394. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50395. this._scene.animationGroups.push(this);
  50396. }
  50397. Object.defineProperty(AnimationGroup.prototype, "from", {
  50398. /**
  50399. * Gets the first frame
  50400. */
  50401. get: function () {
  50402. return this._from;
  50403. },
  50404. enumerable: true,
  50405. configurable: true
  50406. });
  50407. Object.defineProperty(AnimationGroup.prototype, "to", {
  50408. /**
  50409. * Gets the last frame
  50410. */
  50411. get: function () {
  50412. return this._to;
  50413. },
  50414. enumerable: true,
  50415. configurable: true
  50416. });
  50417. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50418. /**
  50419. * Define if the animations are started
  50420. */
  50421. get: function () {
  50422. return this._isStarted;
  50423. },
  50424. enumerable: true,
  50425. configurable: true
  50426. });
  50427. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50428. /**
  50429. * Gets or sets the speed ratio to use for all animations
  50430. */
  50431. get: function () {
  50432. return this._speedRatio;
  50433. },
  50434. /**
  50435. * Gets or sets the speed ratio to use for all animations
  50436. */
  50437. set: function (value) {
  50438. if (this._speedRatio === value) {
  50439. return;
  50440. }
  50441. this._speedRatio = value;
  50442. for (var index = 0; index < this._animatables.length; index++) {
  50443. var animatable = this._animatables[index];
  50444. animatable.speedRatio = this._speedRatio;
  50445. }
  50446. },
  50447. enumerable: true,
  50448. configurable: true
  50449. });
  50450. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50451. /**
  50452. * Gets the targeted animations for this animation group
  50453. */
  50454. get: function () {
  50455. return this._targetedAnimations;
  50456. },
  50457. enumerable: true,
  50458. configurable: true
  50459. });
  50460. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50461. /**
  50462. * returning the list of animatables controlled by this animation group.
  50463. */
  50464. get: function () {
  50465. return this._animatables;
  50466. },
  50467. enumerable: true,
  50468. configurable: true
  50469. });
  50470. /**
  50471. * Add an animation (with its target) in the group
  50472. * @param animation defines the animation we want to add
  50473. * @param target defines the target of the animation
  50474. * @returns the {BABYLON.TargetedAnimation} object
  50475. */
  50476. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50477. var targetedAnimation = {
  50478. animation: animation,
  50479. target: target
  50480. };
  50481. var keys = animation.getKeys();
  50482. if (this._from > keys[0].frame) {
  50483. this._from = keys[0].frame;
  50484. }
  50485. if (this._to < keys[keys.length - 1].frame) {
  50486. this._to = keys[keys.length - 1].frame;
  50487. }
  50488. this._targetedAnimations.push(targetedAnimation);
  50489. return targetedAnimation;
  50490. };
  50491. /**
  50492. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50493. * It can add constant keys at begin or end
  50494. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50495. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50496. */
  50497. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50498. if (beginFrame === void 0) { beginFrame = null; }
  50499. if (endFrame === void 0) { endFrame = null; }
  50500. if (beginFrame == null)
  50501. beginFrame = this._from;
  50502. if (endFrame == null)
  50503. endFrame = this._to;
  50504. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50505. var targetedAnimation = this._targetedAnimations[index];
  50506. var keys = targetedAnimation.animation.getKeys();
  50507. var startKey = keys[0];
  50508. var endKey = keys[keys.length - 1];
  50509. if (startKey.frame > beginFrame) {
  50510. var newKey = {
  50511. frame: beginFrame,
  50512. value: startKey.value,
  50513. inTangent: startKey.inTangent,
  50514. outTangent: startKey.outTangent,
  50515. interpolation: startKey.interpolation
  50516. };
  50517. keys.splice(0, 0, newKey);
  50518. }
  50519. if (endKey.frame < endFrame) {
  50520. var newKey = {
  50521. frame: endFrame,
  50522. value: endKey.value,
  50523. inTangent: endKey.outTangent,
  50524. outTangent: endKey.outTangent,
  50525. interpolation: endKey.interpolation
  50526. };
  50527. keys.push(newKey);
  50528. }
  50529. }
  50530. this._from = beginFrame;
  50531. this._to = endFrame;
  50532. return this;
  50533. };
  50534. /**
  50535. * Start all animations on given targets
  50536. * @param loop defines if animations must loop
  50537. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50538. * @param from defines the from key (optional)
  50539. * @param to defines the to key (optional)
  50540. * @returns the current animation group
  50541. */
  50542. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50543. var _this = this;
  50544. if (loop === void 0) { loop = false; }
  50545. if (speedRatio === void 0) { speedRatio = 1; }
  50546. if (this._isStarted || this._targetedAnimations.length === 0) {
  50547. return this;
  50548. }
  50549. var _loop_1 = function (targetedAnimation) {
  50550. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50551. animatable.onAnimationEnd = function () {
  50552. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50553. _this._checkAnimationGroupEnded(animatable);
  50554. };
  50555. this_1._animatables.push(animatable);
  50556. };
  50557. var this_1 = this;
  50558. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50559. var targetedAnimation = _a[_i];
  50560. _loop_1(targetedAnimation);
  50561. }
  50562. this._speedRatio = speedRatio;
  50563. this._isStarted = true;
  50564. return this;
  50565. };
  50566. /**
  50567. * Pause all animations
  50568. */
  50569. AnimationGroup.prototype.pause = 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.pause();
  50576. }
  50577. return this;
  50578. };
  50579. /**
  50580. * Play all animations to initial state
  50581. * This function will start() the animations if they were not started or will restart() them if they were paused
  50582. * @param loop defines if animations must loop
  50583. */
  50584. AnimationGroup.prototype.play = function (loop) {
  50585. // only if all animatables are ready and exist
  50586. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50587. if (loop !== undefined) {
  50588. for (var index = 0; index < this._animatables.length; index++) {
  50589. var animatable = this._animatables[index];
  50590. animatable.loopAnimation = loop;
  50591. }
  50592. }
  50593. this.restart();
  50594. }
  50595. else {
  50596. this.stop();
  50597. this.start(loop, this._speedRatio);
  50598. }
  50599. return this;
  50600. };
  50601. /**
  50602. * Reset all animations to initial state
  50603. */
  50604. AnimationGroup.prototype.reset = function () {
  50605. if (!this._isStarted) {
  50606. return this;
  50607. }
  50608. for (var index = 0; index < this._animatables.length; index++) {
  50609. var animatable = this._animatables[index];
  50610. animatable.reset();
  50611. }
  50612. return this;
  50613. };
  50614. /**
  50615. * Restart animations from key 0
  50616. */
  50617. AnimationGroup.prototype.restart = function () {
  50618. if (!this._isStarted) {
  50619. return this;
  50620. }
  50621. for (var index = 0; index < this._animatables.length; index++) {
  50622. var animatable = this._animatables[index];
  50623. animatable.restart();
  50624. }
  50625. return this;
  50626. };
  50627. /**
  50628. * Stop all animations
  50629. */
  50630. AnimationGroup.prototype.stop = function () {
  50631. if (!this._isStarted) {
  50632. return this;
  50633. }
  50634. var list = this._animatables.slice();
  50635. for (var index = 0; index < list.length; index++) {
  50636. list[index].stop();
  50637. }
  50638. this._isStarted = false;
  50639. return this;
  50640. };
  50641. /**
  50642. * Set animation weight for all animatables
  50643. * @param weight defines the weight to use
  50644. * @return the animationGroup
  50645. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50646. */
  50647. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50648. for (var index = 0; index < this._animatables.length; index++) {
  50649. var animatable = this._animatables[index];
  50650. animatable.weight = weight;
  50651. }
  50652. return this;
  50653. };
  50654. /**
  50655. * Synchronize and normalize all animatables with a source animatable
  50656. * @param root defines the root animatable to synchronize with
  50657. * @return the animationGroup
  50658. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50659. */
  50660. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50661. for (var index = 0; index < this._animatables.length; index++) {
  50662. var animatable = this._animatables[index];
  50663. animatable.syncWith(root);
  50664. }
  50665. return this;
  50666. };
  50667. /**
  50668. * Goes to a specific frame in this animation group
  50669. * @param frame the frame number to go to
  50670. * @return the animationGroup
  50671. */
  50672. AnimationGroup.prototype.goToFrame = function (frame) {
  50673. if (!this._isStarted) {
  50674. return this;
  50675. }
  50676. for (var index = 0; index < this._animatables.length; index++) {
  50677. var animatable = this._animatables[index];
  50678. animatable.goToFrame(frame);
  50679. }
  50680. return this;
  50681. };
  50682. /**
  50683. * Dispose all associated resources
  50684. */
  50685. AnimationGroup.prototype.dispose = function () {
  50686. this._targetedAnimations = [];
  50687. this._animatables = [];
  50688. var index = this._scene.animationGroups.indexOf(this);
  50689. if (index > -1) {
  50690. this._scene.animationGroups.splice(index, 1);
  50691. }
  50692. };
  50693. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50694. // animatable should be taken out of the array
  50695. var idx = this._animatables.indexOf(animatable);
  50696. if (idx > -1) {
  50697. this._animatables.splice(idx, 1);
  50698. }
  50699. // all animatables were removed? animation group ended!
  50700. if (this._animatables.length === 0) {
  50701. this._isStarted = false;
  50702. this.onAnimationGroupEndObservable.notifyObservers(this);
  50703. }
  50704. };
  50705. return AnimationGroup;
  50706. }());
  50707. BABYLON.AnimationGroup = AnimationGroup;
  50708. })(BABYLON || (BABYLON = {}));
  50709. //# sourceMappingURL=babylon.animationGroup.js.map
  50710. var BABYLON;
  50711. (function (BABYLON) {
  50712. /**
  50713. * Defines a runtime animation
  50714. */
  50715. var RuntimeAnimation = /** @class */ (function () {
  50716. /**
  50717. * Create a new RuntimeAnimation object
  50718. * @param target defines the target of the animation
  50719. * @param animation defines the source animation object
  50720. * @param scene defines the hosting scene
  50721. * @param host defines the initiating Animatable
  50722. */
  50723. function RuntimeAnimation(target, animation, scene, host) {
  50724. var _this = this;
  50725. this._events = new Array();
  50726. /**
  50727. * The current frame of the runtime animation
  50728. */
  50729. this._currentFrame = 0;
  50730. /**
  50731. * The original value of the runtime animation
  50732. */
  50733. this._originalValue = new Array();
  50734. /**
  50735. * The offsets cache of the runtime animation
  50736. */
  50737. this._offsetsCache = {};
  50738. /**
  50739. * The high limits cache of the runtime animation
  50740. */
  50741. this._highLimitsCache = {};
  50742. /**
  50743. * Specifies if the runtime animation has been stopped
  50744. */
  50745. this._stopped = false;
  50746. /**
  50747. * The blending factor of the runtime animation
  50748. */
  50749. this._blendingFactor = 0;
  50750. /**
  50751. * The target path of the runtime animation
  50752. */
  50753. this._targetPath = "";
  50754. /**
  50755. * The weight of the runtime animation
  50756. */
  50757. this._weight = 1.0;
  50758. /**
  50759. * The ratio offset of the runtime animation
  50760. */
  50761. this._ratioOffset = 0;
  50762. /**
  50763. * The previous delay of the runtime animation
  50764. */
  50765. this._previousDelay = 0;
  50766. /**
  50767. * The previous ratio of the runtime animation
  50768. */
  50769. this._previousRatio = 0;
  50770. this._animation = animation;
  50771. this._target = target;
  50772. this._scene = scene;
  50773. this._host = host;
  50774. animation._runtimeAnimations.push(this);
  50775. // Cloning events locally
  50776. var events = animation.getEvents();
  50777. if (events && events.length > 0) {
  50778. events.forEach(function (e) {
  50779. _this._events.push(e._clone());
  50780. });
  50781. }
  50782. }
  50783. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50784. /**
  50785. * Gets the current frame of the runtime animation
  50786. */
  50787. get: function () {
  50788. return this._currentFrame;
  50789. },
  50790. enumerable: true,
  50791. configurable: true
  50792. });
  50793. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50794. /**
  50795. * Gets the weight of the runtime animation
  50796. */
  50797. get: function () {
  50798. return this._weight;
  50799. },
  50800. enumerable: true,
  50801. configurable: true
  50802. });
  50803. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50804. /**
  50805. * Gets the current value of the runtime animation
  50806. */
  50807. get: function () {
  50808. return this._currentValue;
  50809. },
  50810. enumerable: true,
  50811. configurable: true
  50812. });
  50813. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50814. /**
  50815. * Gets the target path of the runtime animation
  50816. */
  50817. get: function () {
  50818. return this._targetPath;
  50819. },
  50820. enumerable: true,
  50821. configurable: true
  50822. });
  50823. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50824. /**
  50825. * Gets the actual target of the runtime animation
  50826. */
  50827. get: function () {
  50828. return this._activeTarget;
  50829. },
  50830. enumerable: true,
  50831. configurable: true
  50832. });
  50833. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50834. /**
  50835. * Gets the animation from the runtime animation
  50836. */
  50837. get: function () {
  50838. return this._animation;
  50839. },
  50840. enumerable: true,
  50841. configurable: true
  50842. });
  50843. /**
  50844. * Resets the runtime animation to the beginning
  50845. * @param restoreOriginal defines whether to restore the target property to the original value
  50846. */
  50847. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50848. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50849. if (restoreOriginal) {
  50850. if (this._target instanceof Array) {
  50851. var index = 0;
  50852. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50853. var target = _a[_i];
  50854. if (this._originalValue[index] !== undefined) {
  50855. this._setValue(target, this._originalValue[index], -1);
  50856. }
  50857. index++;
  50858. }
  50859. }
  50860. else {
  50861. if (this._originalValue[0] !== undefined) {
  50862. this._setValue(this._target, this._originalValue[0], -1);
  50863. }
  50864. }
  50865. }
  50866. this._offsetsCache = {};
  50867. this._highLimitsCache = {};
  50868. this._currentFrame = 0;
  50869. this._blendingFactor = 0;
  50870. this._originalValue = new Array();
  50871. // Events
  50872. for (var index = 0; index < this._events.length; index++) {
  50873. this._events[index].isDone = false;
  50874. }
  50875. };
  50876. /**
  50877. * Specifies if the runtime animation is stopped
  50878. * @returns Boolean specifying if the runtime animation is stopped
  50879. */
  50880. RuntimeAnimation.prototype.isStopped = function () {
  50881. return this._stopped;
  50882. };
  50883. /**
  50884. * Disposes of the runtime animation
  50885. */
  50886. RuntimeAnimation.prototype.dispose = function () {
  50887. var index = this._animation.runtimeAnimations.indexOf(this);
  50888. if (index > -1) {
  50889. this._animation.runtimeAnimations.splice(index, 1);
  50890. }
  50891. };
  50892. /**
  50893. * Interpolates the animation from the current frame
  50894. * @param currentFrame The frame to interpolate the animation to
  50895. * @param repeatCount The number of times that the animation should loop
  50896. * @param loopMode The type of looping mode to use
  50897. * @param offsetValue Animation offset value
  50898. * @param highLimitValue The high limit value
  50899. * @returns The interpolated value
  50900. */
  50901. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50902. this._currentFrame = currentFrame;
  50903. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50904. this._workValue = BABYLON.Matrix.Zero();
  50905. }
  50906. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50907. };
  50908. /**
  50909. * Apply the interpolated value to the target
  50910. * @param currentValue defines the value computed by the animation
  50911. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50912. */
  50913. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50914. if (weight === void 0) { weight = 1.0; }
  50915. if (this._target instanceof Array) {
  50916. var index = 0;
  50917. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50918. var target = _a[_i];
  50919. this._setValue(target, currentValue, weight, index);
  50920. index++;
  50921. }
  50922. }
  50923. else {
  50924. this._setValue(this._target, currentValue, weight);
  50925. }
  50926. };
  50927. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50928. if (targetIndex === void 0) { targetIndex = 0; }
  50929. // Set value
  50930. var path;
  50931. var destination;
  50932. var targetPropertyPath = this._animation.targetPropertyPath;
  50933. if (targetPropertyPath.length > 1) {
  50934. var property = target[targetPropertyPath[0]];
  50935. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50936. property = property[targetPropertyPath[index]];
  50937. }
  50938. path = targetPropertyPath[targetPropertyPath.length - 1];
  50939. destination = property;
  50940. }
  50941. else {
  50942. path = targetPropertyPath[0];
  50943. destination = target;
  50944. }
  50945. this._targetPath = path;
  50946. this._activeTarget = destination;
  50947. this._weight = weight;
  50948. if (this._originalValue[targetIndex] === undefined) {
  50949. var originalValue = void 0;
  50950. if (destination.getRestPose && path === "_matrix") { // For bones
  50951. originalValue = destination.getRestPose();
  50952. }
  50953. else {
  50954. originalValue = destination[path];
  50955. }
  50956. if (originalValue && originalValue.clone) {
  50957. this._originalValue[targetIndex] = originalValue.clone();
  50958. }
  50959. else {
  50960. this._originalValue[targetIndex] = originalValue;
  50961. }
  50962. }
  50963. // Blending
  50964. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50965. if (enableBlending && this._blendingFactor <= 1.0) {
  50966. if (!this._originalBlendValue) {
  50967. var originalValue = destination[path];
  50968. if (originalValue.clone) {
  50969. this._originalBlendValue = originalValue.clone();
  50970. }
  50971. else {
  50972. this._originalBlendValue = originalValue;
  50973. }
  50974. }
  50975. if (this._originalBlendValue.m) { // Matrix
  50976. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50977. if (this._currentValue) {
  50978. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50979. }
  50980. else {
  50981. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50982. }
  50983. }
  50984. else {
  50985. if (this._currentValue) {
  50986. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50987. }
  50988. else {
  50989. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50990. }
  50991. }
  50992. }
  50993. else {
  50994. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50995. }
  50996. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50997. this._blendingFactor += blendingSpeed;
  50998. }
  50999. else {
  51000. this._currentValue = currentValue;
  51001. }
  51002. if (weight !== -1.0) {
  51003. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51004. }
  51005. else {
  51006. destination[path] = this._currentValue;
  51007. }
  51008. if (target.markAsDirty) {
  51009. target.markAsDirty(this._animation.targetProperty);
  51010. }
  51011. };
  51012. /**
  51013. * Gets the loop pmode of the runtime animation
  51014. * @returns Loop Mode
  51015. */
  51016. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51017. if (this._target && this._target.animationPropertiesOverride) {
  51018. return this._target.animationPropertiesOverride.loopMode;
  51019. }
  51020. return this._animation.loopMode;
  51021. };
  51022. /**
  51023. * Move the current animation to a given frame
  51024. * @param frame defines the frame to move to
  51025. */
  51026. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51027. var keys = this._animation.getKeys();
  51028. if (frame < keys[0].frame) {
  51029. frame = keys[0].frame;
  51030. }
  51031. else if (frame > keys[keys.length - 1].frame) {
  51032. frame = keys[keys.length - 1].frame;
  51033. }
  51034. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51035. this.setValue(currentValue, -1);
  51036. };
  51037. /**
  51038. * @hidden Internal use only
  51039. */
  51040. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51041. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51042. this._ratioOffset = this._previousRatio - newRatio;
  51043. };
  51044. /**
  51045. * Execute the current animation
  51046. * @param delay defines the delay to add to the current frame
  51047. * @param from defines the lower bound of the animation range
  51048. * @param to defines the upper bound of the animation range
  51049. * @param loop defines if the current animation must loop
  51050. * @param speedRatio defines the current speed ratio
  51051. * @param weight defines the weight of the animation (default is -1 so no weight)
  51052. * @returns a boolean indicating if the animation has ended
  51053. */
  51054. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51055. if (weight === void 0) { weight = -1.0; }
  51056. var targetPropertyPath = this._animation.targetPropertyPath;
  51057. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51058. this._stopped = true;
  51059. return false;
  51060. }
  51061. var returnValue = true;
  51062. var keys = this._animation.getKeys();
  51063. // Adding a start key at frame 0 if missing
  51064. if (keys[0].frame !== 0) {
  51065. var newKey = { frame: 0, value: keys[0].value };
  51066. keys.splice(0, 0, newKey);
  51067. }
  51068. // Check limits
  51069. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51070. from = keys[0].frame;
  51071. }
  51072. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51073. to = keys[keys.length - 1].frame;
  51074. }
  51075. //to and from cannot be the same key
  51076. if (from === to) {
  51077. if (from > keys[0].frame) {
  51078. from--;
  51079. }
  51080. else if (to < keys[keys.length - 1].frame) {
  51081. to++;
  51082. }
  51083. }
  51084. // Compute ratio
  51085. var range = to - from;
  51086. var offsetValue;
  51087. // ratio represents the frame delta between from and to
  51088. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51089. var highLimitValue = 0;
  51090. this._previousDelay = delay;
  51091. this._previousRatio = ratio;
  51092. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51093. returnValue = false;
  51094. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51095. }
  51096. else {
  51097. // Get max value if required
  51098. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51099. var keyOffset = to.toString() + from.toString();
  51100. if (!this._offsetsCache[keyOffset]) {
  51101. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51102. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51103. switch (this._animation.dataType) {
  51104. // Float
  51105. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51106. this._offsetsCache[keyOffset] = toValue - fromValue;
  51107. break;
  51108. // Quaternion
  51109. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51110. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51111. break;
  51112. // Vector3
  51113. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51114. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51115. // Vector2
  51116. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51117. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51118. // Size
  51119. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51120. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51121. // Color3
  51122. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51123. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51124. default:
  51125. break;
  51126. }
  51127. this._highLimitsCache[keyOffset] = toValue;
  51128. }
  51129. highLimitValue = this._highLimitsCache[keyOffset];
  51130. offsetValue = this._offsetsCache[keyOffset];
  51131. }
  51132. }
  51133. if (offsetValue === undefined) {
  51134. switch (this._animation.dataType) {
  51135. // Float
  51136. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51137. offsetValue = 0;
  51138. break;
  51139. // Quaternion
  51140. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51141. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51142. break;
  51143. // Vector3
  51144. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51145. offsetValue = BABYLON.Vector3.Zero();
  51146. break;
  51147. // Vector2
  51148. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51149. offsetValue = BABYLON.Vector2.Zero();
  51150. break;
  51151. // Size
  51152. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51153. offsetValue = BABYLON.Size.Zero();
  51154. break;
  51155. // Color3
  51156. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51157. offsetValue = BABYLON.Color3.Black();
  51158. }
  51159. }
  51160. // Compute value
  51161. var repeatCount = (ratio / range) >> 0;
  51162. var currentFrame = returnValue ? from + ratio % range : to;
  51163. // Need to normalize?
  51164. if (this._host && this._host.syncRoot) {
  51165. var syncRoot = this._host.syncRoot;
  51166. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51167. currentFrame = from + (to - from) * hostNormalizedFrame;
  51168. }
  51169. // Reset events if looping
  51170. var events = this._events;
  51171. if (range > 0 && this.currentFrame > currentFrame ||
  51172. range < 0 && this.currentFrame < currentFrame) {
  51173. // Need to reset animation events
  51174. for (var index = 0; index < events.length; index++) {
  51175. if (!events[index].onlyOnce) {
  51176. // reset event, the animation is looping
  51177. events[index].isDone = false;
  51178. }
  51179. }
  51180. }
  51181. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51182. // Set value
  51183. this.setValue(currentValue, weight);
  51184. // Check events
  51185. for (var index = 0; index < events.length; index++) {
  51186. // Make sure current frame has passed event frame and that event frame is within the current range
  51187. // Also, handle both forward and reverse animations
  51188. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51189. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51190. var event = events[index];
  51191. if (!event.isDone) {
  51192. // If event should be done only once, remove it.
  51193. if (event.onlyOnce) {
  51194. events.splice(index, 1);
  51195. index--;
  51196. }
  51197. event.isDone = true;
  51198. event.action();
  51199. } // Don't do anything if the event has already be done.
  51200. }
  51201. }
  51202. if (!returnValue) {
  51203. this._stopped = true;
  51204. }
  51205. return returnValue;
  51206. };
  51207. return RuntimeAnimation;
  51208. }());
  51209. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51210. })(BABYLON || (BABYLON = {}));
  51211. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51212. var BABYLON;
  51213. (function (BABYLON) {
  51214. var Animatable = /** @class */ (function () {
  51215. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51216. if (fromFrame === void 0) { fromFrame = 0; }
  51217. if (toFrame === void 0) { toFrame = 100; }
  51218. if (loopAnimation === void 0) { loopAnimation = false; }
  51219. if (speedRatio === void 0) { speedRatio = 1.0; }
  51220. this.target = target;
  51221. this.fromFrame = fromFrame;
  51222. this.toFrame = toFrame;
  51223. this.loopAnimation = loopAnimation;
  51224. this.onAnimationEnd = onAnimationEnd;
  51225. this._localDelayOffset = null;
  51226. this._pausedDelay = null;
  51227. this._runtimeAnimations = new Array();
  51228. this._paused = false;
  51229. this._speedRatio = 1;
  51230. this._weight = -1.0;
  51231. this.animationStarted = false;
  51232. /**
  51233. * Observer raised when the animation ends
  51234. */
  51235. this.onAnimationEndObservable = new BABYLON.Observable();
  51236. this._scene = scene;
  51237. if (animations) {
  51238. this.appendAnimations(target, animations);
  51239. }
  51240. this._speedRatio = speedRatio;
  51241. scene._activeAnimatables.push(this);
  51242. }
  51243. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51244. /**
  51245. * Gets the root Animatable used to synchronize and normalize animations
  51246. */
  51247. get: function () {
  51248. return this._syncRoot;
  51249. },
  51250. enumerable: true,
  51251. configurable: true
  51252. });
  51253. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51254. /**
  51255. * Gets the current frame of the first RuntimeAnimation
  51256. * Used to synchronize Animatables
  51257. */
  51258. get: function () {
  51259. if (this._runtimeAnimations.length === 0) {
  51260. return 0;
  51261. }
  51262. return this._runtimeAnimations[0].currentFrame;
  51263. },
  51264. enumerable: true,
  51265. configurable: true
  51266. });
  51267. Object.defineProperty(Animatable.prototype, "weight", {
  51268. /**
  51269. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51270. */
  51271. get: function () {
  51272. return this._weight;
  51273. },
  51274. set: function (value) {
  51275. if (value === -1) { // -1 is ok and means no weight
  51276. this._weight = -1;
  51277. return;
  51278. }
  51279. // Else weight must be in [0, 1] range
  51280. this._weight = Math.min(Math.max(value, 0), 1.0);
  51281. },
  51282. enumerable: true,
  51283. configurable: true
  51284. });
  51285. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51286. /**
  51287. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51288. */
  51289. get: function () {
  51290. return this._speedRatio;
  51291. },
  51292. set: function (value) {
  51293. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51294. var animation = this._runtimeAnimations[index];
  51295. animation._prepareForSpeedRatioChange(value);
  51296. }
  51297. this._speedRatio = value;
  51298. },
  51299. enumerable: true,
  51300. configurable: true
  51301. });
  51302. // Methods
  51303. /**
  51304. * Synchronize and normalize current Animatable with a source Animatable
  51305. * This is useful when using animation weights and when animations are not of the same length
  51306. * @param root defines the root Animatable to synchronize with
  51307. * @returns the current Animatable
  51308. */
  51309. Animatable.prototype.syncWith = function (root) {
  51310. this._syncRoot = root;
  51311. if (root) {
  51312. // Make sure this animatable will animate after the root
  51313. var index = this._scene._activeAnimatables.indexOf(this);
  51314. if (index > -1) {
  51315. this._scene._activeAnimatables.splice(index, 1);
  51316. this._scene._activeAnimatables.push(this);
  51317. }
  51318. }
  51319. return this;
  51320. };
  51321. Animatable.prototype.getAnimations = function () {
  51322. return this._runtimeAnimations;
  51323. };
  51324. Animatable.prototype.appendAnimations = function (target, animations) {
  51325. for (var index = 0; index < animations.length; index++) {
  51326. var animation = animations[index];
  51327. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51328. }
  51329. };
  51330. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51331. var runtimeAnimations = this._runtimeAnimations;
  51332. for (var index = 0; index < runtimeAnimations.length; index++) {
  51333. if (runtimeAnimations[index].animation.targetProperty === property) {
  51334. return runtimeAnimations[index].animation;
  51335. }
  51336. }
  51337. return null;
  51338. };
  51339. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51340. var runtimeAnimations = this._runtimeAnimations;
  51341. for (var index = 0; index < runtimeAnimations.length; index++) {
  51342. if (runtimeAnimations[index].animation.targetProperty === property) {
  51343. return runtimeAnimations[index];
  51344. }
  51345. }
  51346. return null;
  51347. };
  51348. Animatable.prototype.reset = function () {
  51349. var runtimeAnimations = this._runtimeAnimations;
  51350. for (var index = 0; index < runtimeAnimations.length; index++) {
  51351. runtimeAnimations[index].reset(true);
  51352. }
  51353. this._localDelayOffset = null;
  51354. this._pausedDelay = null;
  51355. };
  51356. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51357. var runtimeAnimations = this._runtimeAnimations;
  51358. for (var index = 0; index < runtimeAnimations.length; index++) {
  51359. runtimeAnimations[index].animation.enableBlending = true;
  51360. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51361. }
  51362. };
  51363. Animatable.prototype.disableBlending = function () {
  51364. var runtimeAnimations = this._runtimeAnimations;
  51365. for (var index = 0; index < runtimeAnimations.length; index++) {
  51366. runtimeAnimations[index].animation.enableBlending = false;
  51367. }
  51368. };
  51369. Animatable.prototype.goToFrame = function (frame) {
  51370. var runtimeAnimations = this._runtimeAnimations;
  51371. if (runtimeAnimations[0]) {
  51372. var fps = runtimeAnimations[0].animation.framePerSecond;
  51373. var currentFrame = runtimeAnimations[0].currentFrame;
  51374. var adjustTime = frame - currentFrame;
  51375. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51376. if (this._localDelayOffset === null) {
  51377. this._localDelayOffset = 0;
  51378. }
  51379. this._localDelayOffset -= delay;
  51380. }
  51381. for (var index = 0; index < runtimeAnimations.length; index++) {
  51382. runtimeAnimations[index].goToFrame(frame);
  51383. }
  51384. };
  51385. Animatable.prototype.pause = function () {
  51386. if (this._paused) {
  51387. return;
  51388. }
  51389. this._paused = true;
  51390. };
  51391. Animatable.prototype.restart = function () {
  51392. this._paused = false;
  51393. };
  51394. Animatable.prototype._raiseOnAnimationEnd = function () {
  51395. if (this.onAnimationEnd) {
  51396. this.onAnimationEnd();
  51397. }
  51398. this.onAnimationEndObservable.notifyObservers(this);
  51399. };
  51400. Animatable.prototype.stop = function (animationName) {
  51401. if (animationName) {
  51402. var idx = this._scene._activeAnimatables.indexOf(this);
  51403. if (idx > -1) {
  51404. var runtimeAnimations = this._runtimeAnimations;
  51405. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51406. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51407. continue;
  51408. }
  51409. runtimeAnimations[index].dispose();
  51410. runtimeAnimations.splice(index, 1);
  51411. }
  51412. if (runtimeAnimations.length == 0) {
  51413. this._scene._activeAnimatables.splice(idx, 1);
  51414. this._raiseOnAnimationEnd();
  51415. }
  51416. }
  51417. }
  51418. else {
  51419. var index = this._scene._activeAnimatables.indexOf(this);
  51420. if (index > -1) {
  51421. this._scene._activeAnimatables.splice(index, 1);
  51422. var runtimeAnimations = this._runtimeAnimations;
  51423. for (var index = 0; index < runtimeAnimations.length; index++) {
  51424. runtimeAnimations[index].dispose();
  51425. }
  51426. this._raiseOnAnimationEnd();
  51427. }
  51428. }
  51429. };
  51430. /**
  51431. * Wait asynchronously for the animation to end
  51432. * @returns a promise which will be fullfilled when the animation ends
  51433. */
  51434. Animatable.prototype.waitAsync = function () {
  51435. var _this = this;
  51436. return new Promise(function (resolve, reject) {
  51437. _this.onAnimationEndObservable.add(function () {
  51438. resolve(_this);
  51439. }, undefined, undefined, _this, true);
  51440. });
  51441. };
  51442. /** @hidden */
  51443. Animatable.prototype._animate = function (delay) {
  51444. if (this._paused) {
  51445. this.animationStarted = false;
  51446. if (this._pausedDelay === null) {
  51447. this._pausedDelay = delay;
  51448. }
  51449. return true;
  51450. }
  51451. if (this._localDelayOffset === null) {
  51452. this._localDelayOffset = delay;
  51453. this._pausedDelay = null;
  51454. }
  51455. else if (this._pausedDelay !== null) {
  51456. this._localDelayOffset += delay - this._pausedDelay;
  51457. this._pausedDelay = null;
  51458. }
  51459. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51460. return true;
  51461. }
  51462. // Animating
  51463. var running = false;
  51464. var runtimeAnimations = this._runtimeAnimations;
  51465. var index;
  51466. for (index = 0; index < runtimeAnimations.length; index++) {
  51467. var animation = runtimeAnimations[index];
  51468. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51469. running = running || isRunning;
  51470. }
  51471. this.animationStarted = running;
  51472. if (!running) {
  51473. // Remove from active animatables
  51474. index = this._scene._activeAnimatables.indexOf(this);
  51475. this._scene._activeAnimatables.splice(index, 1);
  51476. // Dispose all runtime animations
  51477. for (index = 0; index < runtimeAnimations.length; index++) {
  51478. runtimeAnimations[index].dispose();
  51479. }
  51480. this._raiseOnAnimationEnd();
  51481. this.onAnimationEnd = null;
  51482. this.onAnimationEndObservable.clear();
  51483. }
  51484. return running;
  51485. };
  51486. return Animatable;
  51487. }());
  51488. BABYLON.Animatable = Animatable;
  51489. })(BABYLON || (BABYLON = {}));
  51490. //# sourceMappingURL=babylon.animatable.js.map
  51491. var BABYLON;
  51492. (function (BABYLON) {
  51493. var EasingFunction = /** @class */ (function () {
  51494. function EasingFunction() {
  51495. // Properties
  51496. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51497. }
  51498. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51499. get: function () {
  51500. return EasingFunction._EASINGMODE_EASEIN;
  51501. },
  51502. enumerable: true,
  51503. configurable: true
  51504. });
  51505. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51506. get: function () {
  51507. return EasingFunction._EASINGMODE_EASEOUT;
  51508. },
  51509. enumerable: true,
  51510. configurable: true
  51511. });
  51512. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51513. get: function () {
  51514. return EasingFunction._EASINGMODE_EASEINOUT;
  51515. },
  51516. enumerable: true,
  51517. configurable: true
  51518. });
  51519. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51520. var n = Math.min(Math.max(easingMode, 0), 2);
  51521. this._easingMode = n;
  51522. };
  51523. EasingFunction.prototype.getEasingMode = function () {
  51524. return this._easingMode;
  51525. };
  51526. EasingFunction.prototype.easeInCore = function (gradient) {
  51527. throw new Error('You must implement this method');
  51528. };
  51529. EasingFunction.prototype.ease = function (gradient) {
  51530. switch (this._easingMode) {
  51531. case EasingFunction.EASINGMODE_EASEIN:
  51532. return this.easeInCore(gradient);
  51533. case EasingFunction.EASINGMODE_EASEOUT:
  51534. return (1 - this.easeInCore(1 - gradient));
  51535. }
  51536. if (gradient >= 0.5) {
  51537. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51538. }
  51539. return (this.easeInCore(gradient * 2) * 0.5);
  51540. };
  51541. //Statics
  51542. EasingFunction._EASINGMODE_EASEIN = 0;
  51543. EasingFunction._EASINGMODE_EASEOUT = 1;
  51544. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51545. return EasingFunction;
  51546. }());
  51547. BABYLON.EasingFunction = EasingFunction;
  51548. var CircleEase = /** @class */ (function (_super) {
  51549. __extends(CircleEase, _super);
  51550. function CircleEase() {
  51551. return _super !== null && _super.apply(this, arguments) || this;
  51552. }
  51553. CircleEase.prototype.easeInCore = function (gradient) {
  51554. gradient = Math.max(0, Math.min(1, gradient));
  51555. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51556. };
  51557. return CircleEase;
  51558. }(EasingFunction));
  51559. BABYLON.CircleEase = CircleEase;
  51560. var BackEase = /** @class */ (function (_super) {
  51561. __extends(BackEase, _super);
  51562. function BackEase(amplitude) {
  51563. if (amplitude === void 0) { amplitude = 1; }
  51564. var _this = _super.call(this) || this;
  51565. _this.amplitude = amplitude;
  51566. return _this;
  51567. }
  51568. BackEase.prototype.easeInCore = function (gradient) {
  51569. var num = Math.max(0, this.amplitude);
  51570. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51571. };
  51572. return BackEase;
  51573. }(EasingFunction));
  51574. BABYLON.BackEase = BackEase;
  51575. var BounceEase = /** @class */ (function (_super) {
  51576. __extends(BounceEase, _super);
  51577. function BounceEase(bounces, bounciness) {
  51578. if (bounces === void 0) { bounces = 3; }
  51579. if (bounciness === void 0) { bounciness = 2; }
  51580. var _this = _super.call(this) || this;
  51581. _this.bounces = bounces;
  51582. _this.bounciness = bounciness;
  51583. return _this;
  51584. }
  51585. BounceEase.prototype.easeInCore = function (gradient) {
  51586. var y = Math.max(0.0, this.bounces);
  51587. var bounciness = this.bounciness;
  51588. if (bounciness <= 1.0) {
  51589. bounciness = 1.001;
  51590. }
  51591. var num9 = Math.pow(bounciness, y);
  51592. var num5 = 1.0 - bounciness;
  51593. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51594. var num15 = gradient * num4;
  51595. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51596. var num3 = Math.floor(num65);
  51597. var num13 = num3 + 1.0;
  51598. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51599. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51600. var num7 = (num8 + num12) * 0.5;
  51601. var num6 = gradient - num7;
  51602. var num2 = num7 - num8;
  51603. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51604. };
  51605. return BounceEase;
  51606. }(EasingFunction));
  51607. BABYLON.BounceEase = BounceEase;
  51608. var CubicEase = /** @class */ (function (_super) {
  51609. __extends(CubicEase, _super);
  51610. function CubicEase() {
  51611. return _super !== null && _super.apply(this, arguments) || this;
  51612. }
  51613. CubicEase.prototype.easeInCore = function (gradient) {
  51614. return (gradient * gradient * gradient);
  51615. };
  51616. return CubicEase;
  51617. }(EasingFunction));
  51618. BABYLON.CubicEase = CubicEase;
  51619. var ElasticEase = /** @class */ (function (_super) {
  51620. __extends(ElasticEase, _super);
  51621. function ElasticEase(oscillations, springiness) {
  51622. if (oscillations === void 0) { oscillations = 3; }
  51623. if (springiness === void 0) { springiness = 3; }
  51624. var _this = _super.call(this) || this;
  51625. _this.oscillations = oscillations;
  51626. _this.springiness = springiness;
  51627. return _this;
  51628. }
  51629. ElasticEase.prototype.easeInCore = function (gradient) {
  51630. var num2;
  51631. var num3 = Math.max(0.0, this.oscillations);
  51632. var num = Math.max(0.0, this.springiness);
  51633. if (num == 0) {
  51634. num2 = gradient;
  51635. }
  51636. else {
  51637. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51638. }
  51639. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51640. };
  51641. return ElasticEase;
  51642. }(EasingFunction));
  51643. BABYLON.ElasticEase = ElasticEase;
  51644. var ExponentialEase = /** @class */ (function (_super) {
  51645. __extends(ExponentialEase, _super);
  51646. function ExponentialEase(exponent) {
  51647. if (exponent === void 0) { exponent = 2; }
  51648. var _this = _super.call(this) || this;
  51649. _this.exponent = exponent;
  51650. return _this;
  51651. }
  51652. ExponentialEase.prototype.easeInCore = function (gradient) {
  51653. if (this.exponent <= 0) {
  51654. return gradient;
  51655. }
  51656. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51657. };
  51658. return ExponentialEase;
  51659. }(EasingFunction));
  51660. BABYLON.ExponentialEase = ExponentialEase;
  51661. var PowerEase = /** @class */ (function (_super) {
  51662. __extends(PowerEase, _super);
  51663. function PowerEase(power) {
  51664. if (power === void 0) { power = 2; }
  51665. var _this = _super.call(this) || this;
  51666. _this.power = power;
  51667. return _this;
  51668. }
  51669. PowerEase.prototype.easeInCore = function (gradient) {
  51670. var y = Math.max(0.0, this.power);
  51671. return Math.pow(gradient, y);
  51672. };
  51673. return PowerEase;
  51674. }(EasingFunction));
  51675. BABYLON.PowerEase = PowerEase;
  51676. var QuadraticEase = /** @class */ (function (_super) {
  51677. __extends(QuadraticEase, _super);
  51678. function QuadraticEase() {
  51679. return _super !== null && _super.apply(this, arguments) || this;
  51680. }
  51681. QuadraticEase.prototype.easeInCore = function (gradient) {
  51682. return (gradient * gradient);
  51683. };
  51684. return QuadraticEase;
  51685. }(EasingFunction));
  51686. BABYLON.QuadraticEase = QuadraticEase;
  51687. var QuarticEase = /** @class */ (function (_super) {
  51688. __extends(QuarticEase, _super);
  51689. function QuarticEase() {
  51690. return _super !== null && _super.apply(this, arguments) || this;
  51691. }
  51692. QuarticEase.prototype.easeInCore = function (gradient) {
  51693. return (gradient * gradient * gradient * gradient);
  51694. };
  51695. return QuarticEase;
  51696. }(EasingFunction));
  51697. BABYLON.QuarticEase = QuarticEase;
  51698. var QuinticEase = /** @class */ (function (_super) {
  51699. __extends(QuinticEase, _super);
  51700. function QuinticEase() {
  51701. return _super !== null && _super.apply(this, arguments) || this;
  51702. }
  51703. QuinticEase.prototype.easeInCore = function (gradient) {
  51704. return (gradient * gradient * gradient * gradient * gradient);
  51705. };
  51706. return QuinticEase;
  51707. }(EasingFunction));
  51708. BABYLON.QuinticEase = QuinticEase;
  51709. var SineEase = /** @class */ (function (_super) {
  51710. __extends(SineEase, _super);
  51711. function SineEase() {
  51712. return _super !== null && _super.apply(this, arguments) || this;
  51713. }
  51714. SineEase.prototype.easeInCore = function (gradient) {
  51715. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51716. };
  51717. return SineEase;
  51718. }(EasingFunction));
  51719. BABYLON.SineEase = SineEase;
  51720. var BezierCurveEase = /** @class */ (function (_super) {
  51721. __extends(BezierCurveEase, _super);
  51722. function BezierCurveEase(x1, y1, x2, y2) {
  51723. if (x1 === void 0) { x1 = 0; }
  51724. if (y1 === void 0) { y1 = 0; }
  51725. if (x2 === void 0) { x2 = 1; }
  51726. if (y2 === void 0) { y2 = 1; }
  51727. var _this = _super.call(this) || this;
  51728. _this.x1 = x1;
  51729. _this.y1 = y1;
  51730. _this.x2 = x2;
  51731. _this.y2 = y2;
  51732. return _this;
  51733. }
  51734. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51735. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51736. };
  51737. return BezierCurveEase;
  51738. }(EasingFunction));
  51739. BABYLON.BezierCurveEase = BezierCurveEase;
  51740. })(BABYLON || (BABYLON = {}));
  51741. //# sourceMappingURL=babylon.easing.js.map
  51742. var BABYLON;
  51743. (function (BABYLON) {
  51744. /**
  51745. * A Condition applied to an Action
  51746. */
  51747. var Condition = /** @class */ (function () {
  51748. /**
  51749. * Creates a new Condition
  51750. * @param actionManager the manager of the action the condition is applied to
  51751. */
  51752. function Condition(actionManager) {
  51753. this._actionManager = actionManager;
  51754. }
  51755. /**
  51756. * Check if the current condition is valid
  51757. * @returns a boolean
  51758. */
  51759. Condition.prototype.isValid = function () {
  51760. return true;
  51761. };
  51762. /**
  51763. * Internal only
  51764. * @hidden
  51765. */
  51766. Condition.prototype._getProperty = function (propertyPath) {
  51767. return this._actionManager._getProperty(propertyPath);
  51768. };
  51769. /**
  51770. * Internal only
  51771. * @hidden
  51772. */
  51773. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51774. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51775. };
  51776. /**
  51777. * Serialize placeholder for child classes
  51778. * @returns the serialized object
  51779. */
  51780. Condition.prototype.serialize = function () {
  51781. };
  51782. /**
  51783. * Internal only
  51784. * @hidden
  51785. */
  51786. Condition.prototype._serialize = function (serializedCondition) {
  51787. return {
  51788. type: 2,
  51789. children: [],
  51790. name: serializedCondition.name,
  51791. properties: serializedCondition.properties
  51792. };
  51793. };
  51794. return Condition;
  51795. }());
  51796. BABYLON.Condition = Condition;
  51797. /**
  51798. * Defines specific conditional operators as extensions of Condition
  51799. */
  51800. var ValueCondition = /** @class */ (function (_super) {
  51801. __extends(ValueCondition, _super);
  51802. /**
  51803. * Creates a new ValueCondition
  51804. * @param actionManager manager for the action the condition applies to
  51805. * @param target for the action
  51806. * @param propertyPath path to specify the property of the target the conditional operator uses
  51807. * @param value the value compared by the conditional operator against the current value of the property
  51808. * @param operator the conditional operator, default ValueCondition.IsEqual
  51809. */
  51810. function ValueCondition(actionManager, target,
  51811. /** path to specify the property of the target the conditional operator uses */
  51812. propertyPath,
  51813. /** the value compared by the conditional operator against the current value of the property */
  51814. value,
  51815. /** the conditional operator, default ValueCondition.IsEqual */
  51816. operator) {
  51817. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51818. var _this = _super.call(this, actionManager) || this;
  51819. _this.propertyPath = propertyPath;
  51820. _this.value = value;
  51821. _this.operator = operator;
  51822. _this._target = target;
  51823. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51824. _this._property = _this._getProperty(_this.propertyPath);
  51825. return _this;
  51826. }
  51827. Object.defineProperty(ValueCondition, "IsEqual", {
  51828. /**
  51829. * returns the number for IsEqual
  51830. */
  51831. get: function () {
  51832. return ValueCondition._IsEqual;
  51833. },
  51834. enumerable: true,
  51835. configurable: true
  51836. });
  51837. Object.defineProperty(ValueCondition, "IsDifferent", {
  51838. /**
  51839. * Returns the number for IsDifferent
  51840. */
  51841. get: function () {
  51842. return ValueCondition._IsDifferent;
  51843. },
  51844. enumerable: true,
  51845. configurable: true
  51846. });
  51847. Object.defineProperty(ValueCondition, "IsGreater", {
  51848. /**
  51849. * Returns the number for IsGreater
  51850. */
  51851. get: function () {
  51852. return ValueCondition._IsGreater;
  51853. },
  51854. enumerable: true,
  51855. configurable: true
  51856. });
  51857. Object.defineProperty(ValueCondition, "IsLesser", {
  51858. /**
  51859. * Returns the number for IsLesser
  51860. */
  51861. get: function () {
  51862. return ValueCondition._IsLesser;
  51863. },
  51864. enumerable: true,
  51865. configurable: true
  51866. });
  51867. /**
  51868. * Compares the given value with the property value for the specified conditional operator
  51869. * @returns the result of the comparison
  51870. */
  51871. ValueCondition.prototype.isValid = function () {
  51872. switch (this.operator) {
  51873. case ValueCondition.IsGreater:
  51874. return this._effectiveTarget[this._property] > this.value;
  51875. case ValueCondition.IsLesser:
  51876. return this._effectiveTarget[this._property] < this.value;
  51877. case ValueCondition.IsEqual:
  51878. case ValueCondition.IsDifferent:
  51879. var check;
  51880. if (this.value.equals) {
  51881. check = this.value.equals(this._effectiveTarget[this._property]);
  51882. }
  51883. else {
  51884. check = this.value === this._effectiveTarget[this._property];
  51885. }
  51886. return this.operator === ValueCondition.IsEqual ? check : !check;
  51887. }
  51888. return false;
  51889. };
  51890. /**
  51891. * Serialize the ValueCondition into a JSON compatible object
  51892. * @returns serialization object
  51893. */
  51894. ValueCondition.prototype.serialize = function () {
  51895. return this._serialize({
  51896. name: "ValueCondition",
  51897. properties: [
  51898. BABYLON.Action._GetTargetProperty(this._target),
  51899. { name: "propertyPath", value: this.propertyPath },
  51900. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51901. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51902. ]
  51903. });
  51904. };
  51905. /**
  51906. * Gets the name of the conditional operator for the ValueCondition
  51907. * @param operator the conditional operator
  51908. * @returns the name
  51909. */
  51910. ValueCondition.GetOperatorName = function (operator) {
  51911. switch (operator) {
  51912. case ValueCondition._IsEqual: return "IsEqual";
  51913. case ValueCondition._IsDifferent: return "IsDifferent";
  51914. case ValueCondition._IsGreater: return "IsGreater";
  51915. case ValueCondition._IsLesser: return "IsLesser";
  51916. default: return "";
  51917. }
  51918. };
  51919. /**
  51920. * Internal only
  51921. * @hidden
  51922. */
  51923. ValueCondition._IsEqual = 0;
  51924. /**
  51925. * Internal only
  51926. * @hidden
  51927. */
  51928. ValueCondition._IsDifferent = 1;
  51929. /**
  51930. * Internal only
  51931. * @hidden
  51932. */
  51933. ValueCondition._IsGreater = 2;
  51934. /**
  51935. * Internal only
  51936. * @hidden
  51937. */
  51938. ValueCondition._IsLesser = 3;
  51939. return ValueCondition;
  51940. }(Condition));
  51941. BABYLON.ValueCondition = ValueCondition;
  51942. /**
  51943. * Defines a predicate condition as an extension of Condition
  51944. */
  51945. var PredicateCondition = /** @class */ (function (_super) {
  51946. __extends(PredicateCondition, _super);
  51947. /**
  51948. * Creates a new PredicateCondition
  51949. * @param actionManager manager for the action the condition applies to
  51950. * @param predicate defines the predicate function used to validate the condition
  51951. */
  51952. function PredicateCondition(actionManager,
  51953. /** defines the predicate function used to validate the condition */
  51954. predicate) {
  51955. var _this = _super.call(this, actionManager) || this;
  51956. _this.predicate = predicate;
  51957. return _this;
  51958. }
  51959. /**
  51960. * @returns the validity of the predicate condition
  51961. */
  51962. PredicateCondition.prototype.isValid = function () {
  51963. return this.predicate();
  51964. };
  51965. return PredicateCondition;
  51966. }(Condition));
  51967. BABYLON.PredicateCondition = PredicateCondition;
  51968. /**
  51969. * Defines a state condition as an extension of Condition
  51970. */
  51971. var StateCondition = /** @class */ (function (_super) {
  51972. __extends(StateCondition, _super);
  51973. /**
  51974. * Creates a new StateCondition
  51975. * @param actionManager manager for the action the condition applies to
  51976. * @param target of the condition
  51977. * @param value to compare with target state
  51978. */
  51979. function StateCondition(actionManager, target, value) {
  51980. var _this = _super.call(this, actionManager) || this;
  51981. _this.value = value;
  51982. _this._target = target;
  51983. return _this;
  51984. }
  51985. /**
  51986. * @returns the validity of the state
  51987. */
  51988. StateCondition.prototype.isValid = function () {
  51989. return this._target.state === this.value;
  51990. };
  51991. /**
  51992. * Serialize the StateCondition into a JSON compatible object
  51993. * @returns serialization object
  51994. */
  51995. StateCondition.prototype.serialize = function () {
  51996. return this._serialize({
  51997. name: "StateCondition",
  51998. properties: [
  51999. BABYLON.Action._GetTargetProperty(this._target),
  52000. { name: "value", value: this.value }
  52001. ]
  52002. });
  52003. };
  52004. return StateCondition;
  52005. }(Condition));
  52006. BABYLON.StateCondition = StateCondition;
  52007. })(BABYLON || (BABYLON = {}));
  52008. //# sourceMappingURL=babylon.condition.js.map
  52009. var BABYLON;
  52010. (function (BABYLON) {
  52011. /**
  52012. * The action to be carried out following a trigger
  52013. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52014. */
  52015. var Action = /** @class */ (function () {
  52016. /**
  52017. * Creates a new Action
  52018. * @param triggerOptions the trigger, with or without parameters, for the action
  52019. * @param condition an optional determinant of action
  52020. */
  52021. function Action(
  52022. /** the trigger, with or without parameters, for the action */
  52023. triggerOptions, condition) {
  52024. this.triggerOptions = triggerOptions;
  52025. /**
  52026. * An event triggered prior to action being executed.
  52027. */
  52028. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52029. if (triggerOptions.parameter) {
  52030. this.trigger = triggerOptions.trigger;
  52031. this._triggerParameter = triggerOptions.parameter;
  52032. }
  52033. else {
  52034. this.trigger = triggerOptions;
  52035. }
  52036. this._nextActiveAction = this;
  52037. this._condition = condition;
  52038. }
  52039. /**
  52040. * Internal only
  52041. * @hidden
  52042. */
  52043. Action.prototype._prepare = function () {
  52044. };
  52045. /**
  52046. * Gets the trigger parameters
  52047. * @returns the trigger parameters
  52048. */
  52049. Action.prototype.getTriggerParameter = function () {
  52050. return this._triggerParameter;
  52051. };
  52052. /**
  52053. * Internal only - executes current action event
  52054. * @hidden
  52055. */
  52056. Action.prototype._executeCurrent = function (evt) {
  52057. if (this._nextActiveAction._condition) {
  52058. var condition = this._nextActiveAction._condition;
  52059. var currentRenderId = this._actionManager.getScene().getRenderId();
  52060. // We cache the current evaluation for the current frame
  52061. if (condition._evaluationId === currentRenderId) {
  52062. if (!condition._currentResult) {
  52063. return;
  52064. }
  52065. }
  52066. else {
  52067. condition._evaluationId = currentRenderId;
  52068. if (!condition.isValid()) {
  52069. condition._currentResult = false;
  52070. return;
  52071. }
  52072. condition._currentResult = true;
  52073. }
  52074. }
  52075. this.onBeforeExecuteObservable.notifyObservers(this);
  52076. this._nextActiveAction.execute(evt);
  52077. this.skipToNextActiveAction();
  52078. };
  52079. /**
  52080. * Execute placeholder for child classes
  52081. * @param evt optional action event
  52082. */
  52083. Action.prototype.execute = function (evt) {
  52084. };
  52085. /**
  52086. * Skips to next active action
  52087. */
  52088. Action.prototype.skipToNextActiveAction = function () {
  52089. if (this._nextActiveAction._child) {
  52090. if (!this._nextActiveAction._child._actionManager) {
  52091. this._nextActiveAction._child._actionManager = this._actionManager;
  52092. }
  52093. this._nextActiveAction = this._nextActiveAction._child;
  52094. }
  52095. else {
  52096. this._nextActiveAction = this;
  52097. }
  52098. };
  52099. /**
  52100. * Adds action to chain of actions, may be a DoNothingAction
  52101. * @param action defines the next action to execute
  52102. * @returns The action passed in
  52103. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52104. */
  52105. Action.prototype.then = function (action) {
  52106. this._child = action;
  52107. action._actionManager = this._actionManager;
  52108. action._prepare();
  52109. return action;
  52110. };
  52111. /**
  52112. * Internal only
  52113. * @hidden
  52114. */
  52115. Action.prototype._getProperty = function (propertyPath) {
  52116. return this._actionManager._getProperty(propertyPath);
  52117. };
  52118. /**
  52119. * Internal only
  52120. * @hidden
  52121. */
  52122. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52123. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52124. };
  52125. /**
  52126. * Serialize placeholder for child classes
  52127. * @param parent of child
  52128. * @returns the serialized object
  52129. */
  52130. Action.prototype.serialize = function (parent) {
  52131. };
  52132. /**
  52133. * Internal only called by serialize
  52134. * @hidden
  52135. */
  52136. Action.prototype._serialize = function (serializedAction, parent) {
  52137. var serializationObject = {
  52138. type: 1,
  52139. children: [],
  52140. name: serializedAction.name,
  52141. properties: serializedAction.properties || []
  52142. };
  52143. // Serialize child
  52144. if (this._child) {
  52145. this._child.serialize(serializationObject);
  52146. }
  52147. // Check if "this" has a condition
  52148. if (this._condition) {
  52149. var serializedCondition = this._condition.serialize();
  52150. serializedCondition.children.push(serializationObject);
  52151. if (parent) {
  52152. parent.children.push(serializedCondition);
  52153. }
  52154. return serializedCondition;
  52155. }
  52156. if (parent) {
  52157. parent.children.push(serializationObject);
  52158. }
  52159. return serializationObject;
  52160. };
  52161. /**
  52162. * Internal only
  52163. * @hidden
  52164. */
  52165. Action._SerializeValueAsString = function (value) {
  52166. if (typeof value === "number") {
  52167. return value.toString();
  52168. }
  52169. if (typeof value === "boolean") {
  52170. return value ? "true" : "false";
  52171. }
  52172. if (value instanceof BABYLON.Vector2) {
  52173. return value.x + ", " + value.y;
  52174. }
  52175. if (value instanceof BABYLON.Vector3) {
  52176. return value.x + ", " + value.y + ", " + value.z;
  52177. }
  52178. if (value instanceof BABYLON.Color3) {
  52179. return value.r + ", " + value.g + ", " + value.b;
  52180. }
  52181. if (value instanceof BABYLON.Color4) {
  52182. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52183. }
  52184. return value; // string
  52185. };
  52186. /**
  52187. * Internal only
  52188. * @hidden
  52189. */
  52190. Action._GetTargetProperty = function (target) {
  52191. return {
  52192. name: "target",
  52193. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52194. : target instanceof BABYLON.Light ? "LightProperties"
  52195. : target instanceof BABYLON.Camera ? "CameraProperties"
  52196. : "SceneProperties",
  52197. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52198. };
  52199. };
  52200. return Action;
  52201. }());
  52202. BABYLON.Action = Action;
  52203. })(BABYLON || (BABYLON = {}));
  52204. //# sourceMappingURL=babylon.action.js.map
  52205. var BABYLON;
  52206. (function (BABYLON) {
  52207. /**
  52208. * ActionEvent is the event being sent when an action is triggered.
  52209. */
  52210. var ActionEvent = /** @class */ (function () {
  52211. /**
  52212. * Creates a new ActionEvent
  52213. * @param source The mesh or sprite that triggered the action
  52214. * @param pointerX The X mouse cursor position at the time of the event
  52215. * @param pointerY The Y mouse cursor position at the time of the event
  52216. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52217. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52218. * @param additionalData additional data for the event
  52219. */
  52220. function ActionEvent(
  52221. /** The mesh or sprite that triggered the action */
  52222. source,
  52223. /** The X mouse cursor position at the time of the event */
  52224. pointerX,
  52225. /** The Y mouse cursor position at the time of the event */
  52226. pointerY,
  52227. /** The mesh that is currently pointed at (can be null) */
  52228. meshUnderPointer,
  52229. /** the original (browser) event that triggered the ActionEvent */
  52230. sourceEvent,
  52231. /** additional data for the event */
  52232. additionalData) {
  52233. this.source = source;
  52234. this.pointerX = pointerX;
  52235. this.pointerY = pointerY;
  52236. this.meshUnderPointer = meshUnderPointer;
  52237. this.sourceEvent = sourceEvent;
  52238. this.additionalData = additionalData;
  52239. }
  52240. /**
  52241. * Helper function to auto-create an ActionEvent from a source mesh.
  52242. * @param source The source mesh that triggered the event
  52243. * @param evt The original (browser) event
  52244. * @param additionalData additional data for the event
  52245. * @returns the new ActionEvent
  52246. */
  52247. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52248. var scene = source.getScene();
  52249. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52250. };
  52251. /**
  52252. * Helper function to auto-create an ActionEvent from a source sprite
  52253. * @param source The source sprite that triggered the event
  52254. * @param scene Scene associated with the sprite
  52255. * @param evt The original (browser) event
  52256. * @param additionalData additional data for the event
  52257. * @returns the new ActionEvent
  52258. */
  52259. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52260. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52261. };
  52262. /**
  52263. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52264. * @param scene the scene where the event occurred
  52265. * @param evt The original (browser) event
  52266. * @returns the new ActionEvent
  52267. */
  52268. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52269. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52270. };
  52271. /**
  52272. * Helper function to auto-create an ActionEvent from a primitive
  52273. * @param prim defines the target primitive
  52274. * @param pointerPos defines the pointer position
  52275. * @param evt The original (browser) event
  52276. * @param additionalData additional data for the event
  52277. * @returns the new ActionEvent
  52278. */
  52279. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52280. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52281. };
  52282. return ActionEvent;
  52283. }());
  52284. BABYLON.ActionEvent = ActionEvent;
  52285. /**
  52286. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52287. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52288. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52289. */
  52290. var ActionManager = /** @class */ (function () {
  52291. /**
  52292. * Creates a new action manager
  52293. * @param scene defines the hosting scene
  52294. */
  52295. function ActionManager(scene) {
  52296. // Members
  52297. /** Gets the list of actions */
  52298. this.actions = new Array();
  52299. /** Gets the cursor to use when hovering items */
  52300. this.hoverCursor = '';
  52301. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52302. scene._actionManagers.push(this);
  52303. }
  52304. Object.defineProperty(ActionManager, "NothingTrigger", {
  52305. /**
  52306. * Nothing
  52307. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52308. */
  52309. get: function () {
  52310. return ActionManager._NothingTrigger;
  52311. },
  52312. enumerable: true,
  52313. configurable: true
  52314. });
  52315. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52316. /**
  52317. * On pick
  52318. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52319. */
  52320. get: function () {
  52321. return ActionManager._OnPickTrigger;
  52322. },
  52323. enumerable: true,
  52324. configurable: true
  52325. });
  52326. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52327. /**
  52328. * On left pick
  52329. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52330. */
  52331. get: function () {
  52332. return ActionManager._OnLeftPickTrigger;
  52333. },
  52334. enumerable: true,
  52335. configurable: true
  52336. });
  52337. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52338. /**
  52339. * On right pick
  52340. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52341. */
  52342. get: function () {
  52343. return ActionManager._OnRightPickTrigger;
  52344. },
  52345. enumerable: true,
  52346. configurable: true
  52347. });
  52348. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52349. /**
  52350. * On center pick
  52351. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52352. */
  52353. get: function () {
  52354. return ActionManager._OnCenterPickTrigger;
  52355. },
  52356. enumerable: true,
  52357. configurable: true
  52358. });
  52359. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52360. /**
  52361. * On pick down
  52362. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52363. */
  52364. get: function () {
  52365. return ActionManager._OnPickDownTrigger;
  52366. },
  52367. enumerable: true,
  52368. configurable: true
  52369. });
  52370. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52371. /**
  52372. * On double pick
  52373. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52374. */
  52375. get: function () {
  52376. return ActionManager._OnDoublePickTrigger;
  52377. },
  52378. enumerable: true,
  52379. configurable: true
  52380. });
  52381. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52382. /**
  52383. * On pick up
  52384. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52385. */
  52386. get: function () {
  52387. return ActionManager._OnPickUpTrigger;
  52388. },
  52389. enumerable: true,
  52390. configurable: true
  52391. });
  52392. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52393. /**
  52394. * On pick out.
  52395. * This trigger will only be raised if you also declared a OnPickDown
  52396. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52397. */
  52398. get: function () {
  52399. return ActionManager._OnPickOutTrigger;
  52400. },
  52401. enumerable: true,
  52402. configurable: true
  52403. });
  52404. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52405. /**
  52406. * On long press
  52407. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52408. */
  52409. get: function () {
  52410. return ActionManager._OnLongPressTrigger;
  52411. },
  52412. enumerable: true,
  52413. configurable: true
  52414. });
  52415. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52416. /**
  52417. * On pointer over
  52418. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52419. */
  52420. get: function () {
  52421. return ActionManager._OnPointerOverTrigger;
  52422. },
  52423. enumerable: true,
  52424. configurable: true
  52425. });
  52426. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52427. /**
  52428. * On pointer out
  52429. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52430. */
  52431. get: function () {
  52432. return ActionManager._OnPointerOutTrigger;
  52433. },
  52434. enumerable: true,
  52435. configurable: true
  52436. });
  52437. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52438. /**
  52439. * On every frame
  52440. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52441. */
  52442. get: function () {
  52443. return ActionManager._OnEveryFrameTrigger;
  52444. },
  52445. enumerable: true,
  52446. configurable: true
  52447. });
  52448. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52449. /**
  52450. * On intersection enter
  52451. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52452. */
  52453. get: function () {
  52454. return ActionManager._OnIntersectionEnterTrigger;
  52455. },
  52456. enumerable: true,
  52457. configurable: true
  52458. });
  52459. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52460. /**
  52461. * On intersection exit
  52462. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52463. */
  52464. get: function () {
  52465. return ActionManager._OnIntersectionExitTrigger;
  52466. },
  52467. enumerable: true,
  52468. configurable: true
  52469. });
  52470. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52471. /**
  52472. * On key down
  52473. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52474. */
  52475. get: function () {
  52476. return ActionManager._OnKeyDownTrigger;
  52477. },
  52478. enumerable: true,
  52479. configurable: true
  52480. });
  52481. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52482. /**
  52483. * On key up
  52484. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52485. */
  52486. get: function () {
  52487. return ActionManager._OnKeyUpTrigger;
  52488. },
  52489. enumerable: true,
  52490. configurable: true
  52491. });
  52492. // Methods
  52493. /**
  52494. * Releases all associated resources
  52495. */
  52496. ActionManager.prototype.dispose = function () {
  52497. var index = this._scene._actionManagers.indexOf(this);
  52498. for (var i = 0; i < this.actions.length; i++) {
  52499. var action = this.actions[i];
  52500. ActionManager.Triggers[action.trigger]--;
  52501. if (ActionManager.Triggers[action.trigger] === 0) {
  52502. delete ActionManager.Triggers[action.trigger];
  52503. }
  52504. }
  52505. if (index > -1) {
  52506. this._scene._actionManagers.splice(index, 1);
  52507. }
  52508. };
  52509. /**
  52510. * Gets hosting scene
  52511. * @returns the hosting scene
  52512. */
  52513. ActionManager.prototype.getScene = function () {
  52514. return this._scene;
  52515. };
  52516. /**
  52517. * Does this action manager handles actions of any of the given triggers
  52518. * @param triggers defines the triggers to be tested
  52519. * @return a boolean indicating whether one (or more) of the triggers is handled
  52520. */
  52521. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52522. for (var index = 0; index < this.actions.length; index++) {
  52523. var action = this.actions[index];
  52524. if (triggers.indexOf(action.trigger) > -1) {
  52525. return true;
  52526. }
  52527. }
  52528. return false;
  52529. };
  52530. /**
  52531. * Does this action manager handles actions of a given trigger
  52532. * @param trigger defines the trigger to be tested
  52533. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52534. * @return whether the trigger is handled
  52535. */
  52536. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52537. for (var index = 0; index < this.actions.length; index++) {
  52538. var action = this.actions[index];
  52539. if (action.trigger === trigger) {
  52540. if (parameterPredicate) {
  52541. if (parameterPredicate(action.getTriggerParameter())) {
  52542. return true;
  52543. }
  52544. }
  52545. else {
  52546. return true;
  52547. }
  52548. }
  52549. }
  52550. return false;
  52551. };
  52552. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52553. /**
  52554. * Does this action manager has pointer triggers
  52555. */
  52556. get: function () {
  52557. for (var index = 0; index < this.actions.length; index++) {
  52558. var action = this.actions[index];
  52559. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52560. return true;
  52561. }
  52562. }
  52563. return false;
  52564. },
  52565. enumerable: true,
  52566. configurable: true
  52567. });
  52568. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52569. /**
  52570. * Does this action manager has pick triggers
  52571. */
  52572. get: function () {
  52573. for (var index = 0; index < this.actions.length; index++) {
  52574. var action = this.actions[index];
  52575. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52576. return true;
  52577. }
  52578. }
  52579. return false;
  52580. },
  52581. enumerable: true,
  52582. configurable: true
  52583. });
  52584. Object.defineProperty(ActionManager, "HasTriggers", {
  52585. /**
  52586. * Does exist one action manager with at least one trigger
  52587. **/
  52588. get: function () {
  52589. for (var t in ActionManager.Triggers) {
  52590. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52591. return true;
  52592. }
  52593. }
  52594. return false;
  52595. },
  52596. enumerable: true,
  52597. configurable: true
  52598. });
  52599. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52600. /**
  52601. * Does exist one action manager with at least one pick trigger
  52602. **/
  52603. get: function () {
  52604. for (var t in ActionManager.Triggers) {
  52605. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52606. var t_int = parseInt(t);
  52607. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52608. return true;
  52609. }
  52610. }
  52611. }
  52612. return false;
  52613. },
  52614. enumerable: true,
  52615. configurable: true
  52616. });
  52617. /**
  52618. * Does exist one action manager that handles actions of a given trigger
  52619. * @param trigger defines the trigger to be tested
  52620. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52621. **/
  52622. ActionManager.HasSpecificTrigger = function (trigger) {
  52623. for (var t in ActionManager.Triggers) {
  52624. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52625. var t_int = parseInt(t);
  52626. if (t_int === trigger) {
  52627. return true;
  52628. }
  52629. }
  52630. }
  52631. return false;
  52632. };
  52633. /**
  52634. * Registers an action to this action manager
  52635. * @param action defines the action to be registered
  52636. * @return the action amended (prepared) after registration
  52637. */
  52638. ActionManager.prototype.registerAction = function (action) {
  52639. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52640. if (this.getScene().actionManager !== this) {
  52641. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52642. return null;
  52643. }
  52644. }
  52645. this.actions.push(action);
  52646. if (ActionManager.Triggers[action.trigger]) {
  52647. ActionManager.Triggers[action.trigger]++;
  52648. }
  52649. else {
  52650. ActionManager.Triggers[action.trigger] = 1;
  52651. }
  52652. action._actionManager = this;
  52653. action._prepare();
  52654. return action;
  52655. };
  52656. /**
  52657. * Unregisters an action to this action manager
  52658. * @param action defines the action to be unregistered
  52659. * @return a boolean indicating whether the action has been unregistered
  52660. */
  52661. ActionManager.prototype.unregisterAction = function (action) {
  52662. var index = this.actions.indexOf(action);
  52663. if (index !== -1) {
  52664. this.actions.splice(index, 1);
  52665. ActionManager.Triggers[action.trigger] -= 1;
  52666. if (ActionManager.Triggers[action.trigger] === 0) {
  52667. delete ActionManager.Triggers[action.trigger];
  52668. }
  52669. delete action._actionManager;
  52670. return true;
  52671. }
  52672. return false;
  52673. };
  52674. /**
  52675. * Process a specific trigger
  52676. * @param trigger defines the trigger to process
  52677. * @param evt defines the event details to be processed
  52678. */
  52679. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52680. for (var index = 0; index < this.actions.length; index++) {
  52681. var action = this.actions[index];
  52682. if (action.trigger === trigger) {
  52683. if (evt) {
  52684. if (trigger === ActionManager.OnKeyUpTrigger
  52685. || trigger === ActionManager.OnKeyDownTrigger) {
  52686. var parameter = action.getTriggerParameter();
  52687. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52688. if (!parameter.toLowerCase) {
  52689. continue;
  52690. }
  52691. var lowerCase = parameter.toLowerCase();
  52692. if (lowerCase !== evt.sourceEvent.key) {
  52693. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52694. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52695. if (actualkey !== lowerCase) {
  52696. continue;
  52697. }
  52698. }
  52699. }
  52700. }
  52701. }
  52702. action._executeCurrent(evt);
  52703. }
  52704. }
  52705. };
  52706. /** @hidden */
  52707. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52708. var properties = propertyPath.split(".");
  52709. for (var index = 0; index < properties.length - 1; index++) {
  52710. target = target[properties[index]];
  52711. }
  52712. return target;
  52713. };
  52714. /** @hidden */
  52715. ActionManager.prototype._getProperty = function (propertyPath) {
  52716. var properties = propertyPath.split(".");
  52717. return properties[properties.length - 1];
  52718. };
  52719. /**
  52720. * Serialize this manager to a JSON object
  52721. * @param name defines the property name to store this manager
  52722. * @returns a JSON representation of this manager
  52723. */
  52724. ActionManager.prototype.serialize = function (name) {
  52725. var root = {
  52726. children: new Array(),
  52727. name: name,
  52728. type: 3,
  52729. properties: new Array() // Empty for root but required
  52730. };
  52731. for (var i = 0; i < this.actions.length; i++) {
  52732. var triggerObject = {
  52733. type: 0,
  52734. children: new Array(),
  52735. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52736. properties: new Array()
  52737. };
  52738. var triggerOptions = this.actions[i].triggerOptions;
  52739. if (triggerOptions && typeof triggerOptions !== "number") {
  52740. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52741. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52742. }
  52743. else {
  52744. var parameter = {};
  52745. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52746. if (triggerOptions.parameter.mesh) {
  52747. parameter._meshId = triggerOptions.parameter.mesh.id;
  52748. }
  52749. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52750. }
  52751. }
  52752. // Serialize child action, recursively
  52753. this.actions[i].serialize(triggerObject);
  52754. // Add serialized trigger
  52755. root.children.push(triggerObject);
  52756. }
  52757. return root;
  52758. };
  52759. /**
  52760. * Creates a new ActionManager from a JSON data
  52761. * @param parsedActions defines the JSON data to read from
  52762. * @param object defines the hosting mesh
  52763. * @param scene defines the hosting scene
  52764. */
  52765. ActionManager.Parse = function (parsedActions, object, scene) {
  52766. var actionManager = new ActionManager(scene);
  52767. if (object === null)
  52768. scene.actionManager = actionManager;
  52769. else
  52770. object.actionManager = actionManager;
  52771. // instanciate a new object
  52772. var instanciate = function (name, params) {
  52773. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52774. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52775. newInstance.constructor.apply(newInstance, params);
  52776. return newInstance;
  52777. };
  52778. var parseParameter = function (name, value, target, propertyPath) {
  52779. if (propertyPath === null) {
  52780. // String, boolean or float
  52781. var floatValue = parseFloat(value);
  52782. if (value === "true" || value === "false")
  52783. return value === "true";
  52784. else
  52785. return isNaN(floatValue) ? value : floatValue;
  52786. }
  52787. var effectiveTarget = propertyPath.split(".");
  52788. var values = value.split(",");
  52789. // Get effective Target
  52790. for (var i = 0; i < effectiveTarget.length; i++) {
  52791. target = target[effectiveTarget[i]];
  52792. }
  52793. // Return appropriate value with its type
  52794. if (typeof (target) === "boolean")
  52795. return values[0] === "true";
  52796. if (typeof (target) === "string")
  52797. return values[0];
  52798. // Parameters with multiple values such as Vector3 etc.
  52799. var split = new Array();
  52800. for (var i = 0; i < values.length; i++)
  52801. split.push(parseFloat(values[i]));
  52802. if (target instanceof BABYLON.Vector3)
  52803. return BABYLON.Vector3.FromArray(split);
  52804. if (target instanceof BABYLON.Vector4)
  52805. return BABYLON.Vector4.FromArray(split);
  52806. if (target instanceof BABYLON.Color3)
  52807. return BABYLON.Color3.FromArray(split);
  52808. if (target instanceof BABYLON.Color4)
  52809. return BABYLON.Color4.FromArray(split);
  52810. return parseFloat(values[0]);
  52811. };
  52812. // traverse graph per trigger
  52813. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52814. if (combineArray === void 0) { combineArray = null; }
  52815. if (parsedAction.detached)
  52816. return;
  52817. var parameters = new Array();
  52818. var target = null;
  52819. var propertyPath = null;
  52820. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52821. // Parameters
  52822. if (parsedAction.type === 2)
  52823. parameters.push(actionManager);
  52824. else
  52825. parameters.push(trigger);
  52826. if (combine) {
  52827. var actions = new Array();
  52828. for (var j = 0; j < parsedAction.combine.length; j++) {
  52829. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52830. }
  52831. parameters.push(actions);
  52832. }
  52833. else {
  52834. for (var i = 0; i < parsedAction.properties.length; i++) {
  52835. var value = parsedAction.properties[i].value;
  52836. var name = parsedAction.properties[i].name;
  52837. var targetType = parsedAction.properties[i].targetType;
  52838. if (name === "target")
  52839. if (targetType !== null && targetType === "SceneProperties")
  52840. value = target = scene;
  52841. else
  52842. value = target = scene.getNodeByName(value);
  52843. else if (name === "parent")
  52844. value = scene.getNodeByName(value);
  52845. else if (name === "sound")
  52846. value = scene.getSoundByName(value);
  52847. else if (name !== "propertyPath") {
  52848. if (parsedAction.type === 2 && name === "operator")
  52849. value = BABYLON.ValueCondition[value];
  52850. else
  52851. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52852. }
  52853. else {
  52854. propertyPath = value;
  52855. }
  52856. parameters.push(value);
  52857. }
  52858. }
  52859. if (combineArray === null) {
  52860. parameters.push(condition);
  52861. }
  52862. else {
  52863. parameters.push(null);
  52864. }
  52865. // If interpolate value action
  52866. if (parsedAction.name === "InterpolateValueAction") {
  52867. var param = parameters[parameters.length - 2];
  52868. parameters[parameters.length - 1] = param;
  52869. parameters[parameters.length - 2] = condition;
  52870. }
  52871. // Action or condition(s) and not CombineAction
  52872. var newAction = instanciate(parsedAction.name, parameters);
  52873. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52874. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52875. if (action)
  52876. action.then(nothing);
  52877. else
  52878. actionManager.registerAction(nothing);
  52879. action = nothing;
  52880. }
  52881. if (combineArray === null) {
  52882. if (newAction instanceof BABYLON.Condition) {
  52883. condition = newAction;
  52884. newAction = action;
  52885. }
  52886. else {
  52887. condition = null;
  52888. if (action)
  52889. action.then(newAction);
  52890. else
  52891. actionManager.registerAction(newAction);
  52892. }
  52893. }
  52894. else {
  52895. combineArray.push(newAction);
  52896. }
  52897. for (var i = 0; i < parsedAction.children.length; i++)
  52898. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52899. };
  52900. // triggers
  52901. for (var i = 0; i < parsedActions.children.length; i++) {
  52902. var triggerParams;
  52903. var trigger = parsedActions.children[i];
  52904. if (trigger.properties.length > 0) {
  52905. var param = trigger.properties[0].value;
  52906. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52907. if (value._meshId) {
  52908. value.mesh = scene.getMeshByID(value._meshId);
  52909. }
  52910. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52911. }
  52912. else
  52913. triggerParams = ActionManager[trigger.name];
  52914. for (var j = 0; j < trigger.children.length; j++) {
  52915. if (!trigger.detached)
  52916. traverse(trigger.children[j], triggerParams, null, null);
  52917. }
  52918. }
  52919. };
  52920. /**
  52921. * Get a trigger name by index
  52922. * @param trigger defines the trigger index
  52923. * @returns a trigger name
  52924. */
  52925. ActionManager.GetTriggerName = function (trigger) {
  52926. switch (trigger) {
  52927. case 0: return "NothingTrigger";
  52928. case 1: return "OnPickTrigger";
  52929. case 2: return "OnLeftPickTrigger";
  52930. case 3: return "OnRightPickTrigger";
  52931. case 4: return "OnCenterPickTrigger";
  52932. case 5: return "OnPickDownTrigger";
  52933. case 6: return "OnPickUpTrigger";
  52934. case 7: return "OnLongPressTrigger";
  52935. case 8: return "OnPointerOverTrigger";
  52936. case 9: return "OnPointerOutTrigger";
  52937. case 10: return "OnEveryFrameTrigger";
  52938. case 11: return "OnIntersectionEnterTrigger";
  52939. case 12: return "OnIntersectionExitTrigger";
  52940. case 13: return "OnKeyDownTrigger";
  52941. case 14: return "OnKeyUpTrigger";
  52942. case 15: return "OnPickOutTrigger";
  52943. default: return "";
  52944. }
  52945. };
  52946. // Statics
  52947. ActionManager._NothingTrigger = 0;
  52948. ActionManager._OnPickTrigger = 1;
  52949. ActionManager._OnLeftPickTrigger = 2;
  52950. ActionManager._OnRightPickTrigger = 3;
  52951. ActionManager._OnCenterPickTrigger = 4;
  52952. ActionManager._OnPickDownTrigger = 5;
  52953. ActionManager._OnDoublePickTrigger = 6;
  52954. ActionManager._OnPickUpTrigger = 7;
  52955. ActionManager._OnLongPressTrigger = 8;
  52956. ActionManager._OnPointerOverTrigger = 9;
  52957. ActionManager._OnPointerOutTrigger = 10;
  52958. ActionManager._OnEveryFrameTrigger = 11;
  52959. ActionManager._OnIntersectionEnterTrigger = 12;
  52960. ActionManager._OnIntersectionExitTrigger = 13;
  52961. ActionManager._OnKeyDownTrigger = 14;
  52962. ActionManager._OnKeyUpTrigger = 15;
  52963. ActionManager._OnPickOutTrigger = 16;
  52964. /** Gets the list of active triggers */
  52965. ActionManager.Triggers = {};
  52966. return ActionManager;
  52967. }());
  52968. BABYLON.ActionManager = ActionManager;
  52969. })(BABYLON || (BABYLON = {}));
  52970. //# sourceMappingURL=babylon.actionManager.js.map
  52971. var BABYLON;
  52972. (function (BABYLON) {
  52973. var InterpolateValueAction = /** @class */ (function (_super) {
  52974. __extends(InterpolateValueAction, _super);
  52975. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  52976. if (duration === void 0) { duration = 1000; }
  52977. var _this = _super.call(this, triggerOptions, condition) || this;
  52978. _this.propertyPath = propertyPath;
  52979. _this.value = value;
  52980. _this.duration = duration;
  52981. _this.stopOtherAnimations = stopOtherAnimations;
  52982. _this.onInterpolationDone = onInterpolationDone;
  52983. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  52984. _this._target = _this._effectiveTarget = target;
  52985. return _this;
  52986. }
  52987. InterpolateValueAction.prototype._prepare = function () {
  52988. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52989. this._property = this._getProperty(this.propertyPath);
  52990. };
  52991. InterpolateValueAction.prototype.execute = function () {
  52992. var _this = this;
  52993. var scene = this._actionManager.getScene();
  52994. var keys = [
  52995. {
  52996. frame: 0,
  52997. value: this._effectiveTarget[this._property]
  52998. }, {
  52999. frame: 100,
  53000. value: this.value
  53001. }
  53002. ];
  53003. var dataType;
  53004. if (typeof this.value === "number") {
  53005. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53006. }
  53007. else if (this.value instanceof BABYLON.Color3) {
  53008. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53009. }
  53010. else if (this.value instanceof BABYLON.Vector3) {
  53011. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53012. }
  53013. else if (this.value instanceof BABYLON.Matrix) {
  53014. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53015. }
  53016. else if (this.value instanceof BABYLON.Quaternion) {
  53017. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53018. }
  53019. else {
  53020. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53021. return;
  53022. }
  53023. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53024. animation.setKeys(keys);
  53025. if (this.stopOtherAnimations) {
  53026. scene.stopAnimation(this._effectiveTarget);
  53027. }
  53028. var wrapper = function () {
  53029. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53030. if (_this.onInterpolationDone) {
  53031. _this.onInterpolationDone();
  53032. }
  53033. };
  53034. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53035. };
  53036. InterpolateValueAction.prototype.serialize = function (parent) {
  53037. return _super.prototype._serialize.call(this, {
  53038. name: "InterpolateValueAction",
  53039. properties: [
  53040. BABYLON.Action._GetTargetProperty(this._target),
  53041. { name: "propertyPath", value: this.propertyPath },
  53042. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53043. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53044. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53045. ]
  53046. }, parent);
  53047. };
  53048. return InterpolateValueAction;
  53049. }(BABYLON.Action));
  53050. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53051. })(BABYLON || (BABYLON = {}));
  53052. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53053. var BABYLON;
  53054. (function (BABYLON) {
  53055. var SwitchBooleanAction = /** @class */ (function (_super) {
  53056. __extends(SwitchBooleanAction, _super);
  53057. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53058. var _this = _super.call(this, triggerOptions, condition) || this;
  53059. _this.propertyPath = propertyPath;
  53060. _this._target = _this._effectiveTarget = target;
  53061. return _this;
  53062. }
  53063. SwitchBooleanAction.prototype._prepare = function () {
  53064. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53065. this._property = this._getProperty(this.propertyPath);
  53066. };
  53067. SwitchBooleanAction.prototype.execute = function () {
  53068. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53069. };
  53070. SwitchBooleanAction.prototype.serialize = function (parent) {
  53071. return _super.prototype._serialize.call(this, {
  53072. name: "SwitchBooleanAction",
  53073. properties: [
  53074. BABYLON.Action._GetTargetProperty(this._target),
  53075. { name: "propertyPath", value: this.propertyPath }
  53076. ]
  53077. }, parent);
  53078. };
  53079. return SwitchBooleanAction;
  53080. }(BABYLON.Action));
  53081. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53082. var SetStateAction = /** @class */ (function (_super) {
  53083. __extends(SetStateAction, _super);
  53084. function SetStateAction(triggerOptions, target, value, condition) {
  53085. var _this = _super.call(this, triggerOptions, condition) || this;
  53086. _this.value = value;
  53087. _this._target = target;
  53088. return _this;
  53089. }
  53090. SetStateAction.prototype.execute = function () {
  53091. this._target.state = this.value;
  53092. };
  53093. SetStateAction.prototype.serialize = function (parent) {
  53094. return _super.prototype._serialize.call(this, {
  53095. name: "SetStateAction",
  53096. properties: [
  53097. BABYLON.Action._GetTargetProperty(this._target),
  53098. { name: "value", value: this.value }
  53099. ]
  53100. }, parent);
  53101. };
  53102. return SetStateAction;
  53103. }(BABYLON.Action));
  53104. BABYLON.SetStateAction = SetStateAction;
  53105. var SetValueAction = /** @class */ (function (_super) {
  53106. __extends(SetValueAction, _super);
  53107. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53108. var _this = _super.call(this, triggerOptions, condition) || this;
  53109. _this.propertyPath = propertyPath;
  53110. _this.value = value;
  53111. _this._target = _this._effectiveTarget = target;
  53112. return _this;
  53113. }
  53114. SetValueAction.prototype._prepare = function () {
  53115. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53116. this._property = this._getProperty(this.propertyPath);
  53117. };
  53118. SetValueAction.prototype.execute = function () {
  53119. this._effectiveTarget[this._property] = this.value;
  53120. if (this._target.markAsDirty) {
  53121. this._target.markAsDirty(this._property);
  53122. }
  53123. };
  53124. SetValueAction.prototype.serialize = function (parent) {
  53125. return _super.prototype._serialize.call(this, {
  53126. name: "SetValueAction",
  53127. properties: [
  53128. BABYLON.Action._GetTargetProperty(this._target),
  53129. { name: "propertyPath", value: this.propertyPath },
  53130. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53131. ]
  53132. }, parent);
  53133. };
  53134. return SetValueAction;
  53135. }(BABYLON.Action));
  53136. BABYLON.SetValueAction = SetValueAction;
  53137. var IncrementValueAction = /** @class */ (function (_super) {
  53138. __extends(IncrementValueAction, _super);
  53139. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53140. var _this = _super.call(this, triggerOptions, condition) || this;
  53141. _this.propertyPath = propertyPath;
  53142. _this.value = value;
  53143. _this._target = _this._effectiveTarget = target;
  53144. return _this;
  53145. }
  53146. IncrementValueAction.prototype._prepare = function () {
  53147. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53148. this._property = this._getProperty(this.propertyPath);
  53149. if (typeof this._effectiveTarget[this._property] !== "number") {
  53150. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53151. }
  53152. };
  53153. IncrementValueAction.prototype.execute = function () {
  53154. this._effectiveTarget[this._property] += this.value;
  53155. if (this._target.markAsDirty) {
  53156. this._target.markAsDirty(this._property);
  53157. }
  53158. };
  53159. IncrementValueAction.prototype.serialize = function (parent) {
  53160. return _super.prototype._serialize.call(this, {
  53161. name: "IncrementValueAction",
  53162. properties: [
  53163. BABYLON.Action._GetTargetProperty(this._target),
  53164. { name: "propertyPath", value: this.propertyPath },
  53165. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53166. ]
  53167. }, parent);
  53168. };
  53169. return IncrementValueAction;
  53170. }(BABYLON.Action));
  53171. BABYLON.IncrementValueAction = IncrementValueAction;
  53172. var PlayAnimationAction = /** @class */ (function (_super) {
  53173. __extends(PlayAnimationAction, _super);
  53174. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53175. var _this = _super.call(this, triggerOptions, condition) || this;
  53176. _this.from = from;
  53177. _this.to = to;
  53178. _this.loop = loop;
  53179. _this._target = target;
  53180. return _this;
  53181. }
  53182. PlayAnimationAction.prototype._prepare = function () {
  53183. };
  53184. PlayAnimationAction.prototype.execute = function () {
  53185. var scene = this._actionManager.getScene();
  53186. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53187. };
  53188. PlayAnimationAction.prototype.serialize = function (parent) {
  53189. return _super.prototype._serialize.call(this, {
  53190. name: "PlayAnimationAction",
  53191. properties: [
  53192. BABYLON.Action._GetTargetProperty(this._target),
  53193. { name: "from", value: String(this.from) },
  53194. { name: "to", value: String(this.to) },
  53195. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53196. ]
  53197. }, parent);
  53198. };
  53199. return PlayAnimationAction;
  53200. }(BABYLON.Action));
  53201. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53202. var StopAnimationAction = /** @class */ (function (_super) {
  53203. __extends(StopAnimationAction, _super);
  53204. function StopAnimationAction(triggerOptions, target, condition) {
  53205. var _this = _super.call(this, triggerOptions, condition) || this;
  53206. _this._target = target;
  53207. return _this;
  53208. }
  53209. StopAnimationAction.prototype._prepare = function () {
  53210. };
  53211. StopAnimationAction.prototype.execute = function () {
  53212. var scene = this._actionManager.getScene();
  53213. scene.stopAnimation(this._target);
  53214. };
  53215. StopAnimationAction.prototype.serialize = function (parent) {
  53216. return _super.prototype._serialize.call(this, {
  53217. name: "StopAnimationAction",
  53218. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53219. }, parent);
  53220. };
  53221. return StopAnimationAction;
  53222. }(BABYLON.Action));
  53223. BABYLON.StopAnimationAction = StopAnimationAction;
  53224. var DoNothingAction = /** @class */ (function (_super) {
  53225. __extends(DoNothingAction, _super);
  53226. function DoNothingAction(triggerOptions, condition) {
  53227. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53228. return _super.call(this, triggerOptions, condition) || this;
  53229. }
  53230. DoNothingAction.prototype.execute = function () {
  53231. };
  53232. DoNothingAction.prototype.serialize = function (parent) {
  53233. return _super.prototype._serialize.call(this, {
  53234. name: "DoNothingAction",
  53235. properties: []
  53236. }, parent);
  53237. };
  53238. return DoNothingAction;
  53239. }(BABYLON.Action));
  53240. BABYLON.DoNothingAction = DoNothingAction;
  53241. var CombineAction = /** @class */ (function (_super) {
  53242. __extends(CombineAction, _super);
  53243. function CombineAction(triggerOptions, children, condition) {
  53244. var _this = _super.call(this, triggerOptions, condition) || this;
  53245. _this.children = children;
  53246. return _this;
  53247. }
  53248. CombineAction.prototype._prepare = function () {
  53249. for (var index = 0; index < this.children.length; index++) {
  53250. this.children[index]._actionManager = this._actionManager;
  53251. this.children[index]._prepare();
  53252. }
  53253. };
  53254. CombineAction.prototype.execute = function (evt) {
  53255. for (var index = 0; index < this.children.length; index++) {
  53256. this.children[index].execute(evt);
  53257. }
  53258. };
  53259. CombineAction.prototype.serialize = function (parent) {
  53260. var serializationObject = _super.prototype._serialize.call(this, {
  53261. name: "CombineAction",
  53262. properties: [],
  53263. combine: []
  53264. }, parent);
  53265. for (var i = 0; i < this.children.length; i++) {
  53266. serializationObject.combine.push(this.children[i].serialize(null));
  53267. }
  53268. return serializationObject;
  53269. };
  53270. return CombineAction;
  53271. }(BABYLON.Action));
  53272. BABYLON.CombineAction = CombineAction;
  53273. var ExecuteCodeAction = /** @class */ (function (_super) {
  53274. __extends(ExecuteCodeAction, _super);
  53275. function ExecuteCodeAction(triggerOptions, func, condition) {
  53276. var _this = _super.call(this, triggerOptions, condition) || this;
  53277. _this.func = func;
  53278. return _this;
  53279. }
  53280. ExecuteCodeAction.prototype.execute = function (evt) {
  53281. this.func(evt);
  53282. };
  53283. return ExecuteCodeAction;
  53284. }(BABYLON.Action));
  53285. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53286. var SetParentAction = /** @class */ (function (_super) {
  53287. __extends(SetParentAction, _super);
  53288. function SetParentAction(triggerOptions, target, parent, condition) {
  53289. var _this = _super.call(this, triggerOptions, condition) || this;
  53290. _this._target = target;
  53291. _this._parent = parent;
  53292. return _this;
  53293. }
  53294. SetParentAction.prototype._prepare = function () {
  53295. };
  53296. SetParentAction.prototype.execute = function () {
  53297. if (this._target.parent === this._parent) {
  53298. return;
  53299. }
  53300. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53301. invertParentWorldMatrix.invert();
  53302. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53303. this._target.parent = this._parent;
  53304. };
  53305. SetParentAction.prototype.serialize = function (parent) {
  53306. return _super.prototype._serialize.call(this, {
  53307. name: "SetParentAction",
  53308. properties: [
  53309. BABYLON.Action._GetTargetProperty(this._target),
  53310. BABYLON.Action._GetTargetProperty(this._parent),
  53311. ]
  53312. }, parent);
  53313. };
  53314. return SetParentAction;
  53315. }(BABYLON.Action));
  53316. BABYLON.SetParentAction = SetParentAction;
  53317. var PlaySoundAction = /** @class */ (function (_super) {
  53318. __extends(PlaySoundAction, _super);
  53319. function PlaySoundAction(triggerOptions, sound, condition) {
  53320. var _this = _super.call(this, triggerOptions, condition) || this;
  53321. _this._sound = sound;
  53322. return _this;
  53323. }
  53324. PlaySoundAction.prototype._prepare = function () {
  53325. };
  53326. PlaySoundAction.prototype.execute = function () {
  53327. if (this._sound !== undefined)
  53328. this._sound.play();
  53329. };
  53330. PlaySoundAction.prototype.serialize = function (parent) {
  53331. return _super.prototype._serialize.call(this, {
  53332. name: "PlaySoundAction",
  53333. properties: [{ name: "sound", value: this._sound.name }]
  53334. }, parent);
  53335. };
  53336. return PlaySoundAction;
  53337. }(BABYLON.Action));
  53338. BABYLON.PlaySoundAction = PlaySoundAction;
  53339. var StopSoundAction = /** @class */ (function (_super) {
  53340. __extends(StopSoundAction, _super);
  53341. function StopSoundAction(triggerOptions, sound, condition) {
  53342. var _this = _super.call(this, triggerOptions, condition) || this;
  53343. _this._sound = sound;
  53344. return _this;
  53345. }
  53346. StopSoundAction.prototype._prepare = function () {
  53347. };
  53348. StopSoundAction.prototype.execute = function () {
  53349. if (this._sound !== undefined)
  53350. this._sound.stop();
  53351. };
  53352. StopSoundAction.prototype.serialize = function (parent) {
  53353. return _super.prototype._serialize.call(this, {
  53354. name: "StopSoundAction",
  53355. properties: [{ name: "sound", value: this._sound.name }]
  53356. }, parent);
  53357. };
  53358. return StopSoundAction;
  53359. }(BABYLON.Action));
  53360. BABYLON.StopSoundAction = StopSoundAction;
  53361. })(BABYLON || (BABYLON = {}));
  53362. //# sourceMappingURL=babylon.directActions.js.map
  53363. var BABYLON;
  53364. (function (BABYLON) {
  53365. var SpriteManager = /** @class */ (function () {
  53366. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53367. if (epsilon === void 0) { epsilon = 0.01; }
  53368. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53369. this.name = name;
  53370. this.sprites = new Array();
  53371. this.renderingGroupId = 0;
  53372. this.layerMask = 0x0FFFFFFF;
  53373. this.fogEnabled = true;
  53374. this.isPickable = false;
  53375. /**
  53376. * An event triggered when the manager is disposed.
  53377. */
  53378. this.onDisposeObservable = new BABYLON.Observable();
  53379. this._vertexBuffers = {};
  53380. this._capacity = capacity;
  53381. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53382. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53383. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53384. if (cellSize.width && cellSize.height) {
  53385. this.cellWidth = cellSize.width;
  53386. this.cellHeight = cellSize.height;
  53387. }
  53388. else if (cellSize !== undefined) {
  53389. this.cellWidth = cellSize;
  53390. this.cellHeight = cellSize;
  53391. }
  53392. else {
  53393. return;
  53394. }
  53395. this._epsilon = epsilon;
  53396. this._scene = scene;
  53397. this._scene.spriteManagers.push(this);
  53398. var indices = [];
  53399. var index = 0;
  53400. for (var count = 0; count < capacity; count++) {
  53401. indices.push(index);
  53402. indices.push(index + 1);
  53403. indices.push(index + 2);
  53404. indices.push(index);
  53405. indices.push(index + 2);
  53406. indices.push(index + 3);
  53407. index += 4;
  53408. }
  53409. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53410. // VBO
  53411. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53412. this._vertexData = new Float32Array(capacity * 16 * 4);
  53413. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53414. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53415. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53416. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53417. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53418. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53419. this._vertexBuffers["options"] = options;
  53420. this._vertexBuffers["cellInfo"] = cellInfo;
  53421. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53422. // Effects
  53423. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53424. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53425. }
  53426. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53427. set: function (callback) {
  53428. if (this._onDisposeObserver) {
  53429. this.onDisposeObservable.remove(this._onDisposeObserver);
  53430. }
  53431. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53432. },
  53433. enumerable: true,
  53434. configurable: true
  53435. });
  53436. Object.defineProperty(SpriteManager.prototype, "texture", {
  53437. get: function () {
  53438. return this._spriteTexture;
  53439. },
  53440. set: function (value) {
  53441. this._spriteTexture = value;
  53442. },
  53443. enumerable: true,
  53444. configurable: true
  53445. });
  53446. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53447. var arrayOffset = index * 16;
  53448. if (offsetX === 0)
  53449. offsetX = this._epsilon;
  53450. else if (offsetX === 1)
  53451. offsetX = 1 - this._epsilon;
  53452. if (offsetY === 0)
  53453. offsetY = this._epsilon;
  53454. else if (offsetY === 1)
  53455. offsetY = 1 - this._epsilon;
  53456. this._vertexData[arrayOffset] = sprite.position.x;
  53457. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53458. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53459. this._vertexData[arrayOffset + 3] = sprite.angle;
  53460. this._vertexData[arrayOffset + 4] = sprite.width;
  53461. this._vertexData[arrayOffset + 5] = sprite.height;
  53462. this._vertexData[arrayOffset + 6] = offsetX;
  53463. this._vertexData[arrayOffset + 7] = offsetY;
  53464. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53465. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53466. var offset = (sprite.cellIndex / rowSize) >> 0;
  53467. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53468. this._vertexData[arrayOffset + 11] = offset;
  53469. // Color
  53470. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53471. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53472. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53473. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53474. };
  53475. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53476. var count = Math.min(this._capacity, this.sprites.length);
  53477. var min = BABYLON.Vector3.Zero();
  53478. var max = BABYLON.Vector3.Zero();
  53479. var distance = Number.MAX_VALUE;
  53480. var currentSprite = null;
  53481. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53482. var cameraView = camera.getViewMatrix();
  53483. for (var index = 0; index < count; index++) {
  53484. var sprite = this.sprites[index];
  53485. if (!sprite) {
  53486. continue;
  53487. }
  53488. if (predicate) {
  53489. if (!predicate(sprite)) {
  53490. continue;
  53491. }
  53492. }
  53493. else if (!sprite.isPickable) {
  53494. continue;
  53495. }
  53496. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53497. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53498. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53499. if (ray.intersectsBoxMinMax(min, max)) {
  53500. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53501. if (distance > currentDistance) {
  53502. distance = currentDistance;
  53503. currentSprite = sprite;
  53504. if (fastCheck) {
  53505. break;
  53506. }
  53507. }
  53508. }
  53509. }
  53510. if (currentSprite) {
  53511. var result = new BABYLON.PickingInfo();
  53512. result.hit = true;
  53513. result.pickedSprite = currentSprite;
  53514. result.distance = distance;
  53515. return result;
  53516. }
  53517. return null;
  53518. };
  53519. SpriteManager.prototype.render = function () {
  53520. // Check
  53521. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53522. return;
  53523. var engine = this._scene.getEngine();
  53524. var baseSize = this._spriteTexture.getBaseSize();
  53525. // Sprites
  53526. var deltaTime = engine.getDeltaTime();
  53527. var max = Math.min(this._capacity, this.sprites.length);
  53528. var rowSize = baseSize.width / this.cellWidth;
  53529. var offset = 0;
  53530. for (var index = 0; index < max; index++) {
  53531. var sprite = this.sprites[index];
  53532. if (!sprite || !sprite.isVisible) {
  53533. continue;
  53534. }
  53535. sprite._animate(deltaTime);
  53536. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53537. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53538. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53539. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53540. }
  53541. this._buffer.update(this._vertexData);
  53542. // Render
  53543. var effect = this._effectBase;
  53544. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53545. effect = this._effectFog;
  53546. }
  53547. engine.enableEffect(effect);
  53548. var viewMatrix = this._scene.getViewMatrix();
  53549. effect.setTexture("diffuseSampler", this._spriteTexture);
  53550. effect.setMatrix("view", viewMatrix);
  53551. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53552. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53553. // Fog
  53554. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53555. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53556. effect.setColor3("vFogColor", this._scene.fogColor);
  53557. }
  53558. // VBOs
  53559. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53560. // Draw order
  53561. engine.setDepthFunctionToLessOrEqual();
  53562. effect.setBool("alphaTest", true);
  53563. engine.setColorWrite(false);
  53564. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53565. engine.setColorWrite(true);
  53566. effect.setBool("alphaTest", false);
  53567. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53568. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53569. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53570. };
  53571. SpriteManager.prototype.dispose = function () {
  53572. if (this._buffer) {
  53573. this._buffer.dispose();
  53574. this._buffer = null;
  53575. }
  53576. if (this._indexBuffer) {
  53577. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53578. this._indexBuffer = null;
  53579. }
  53580. if (this._spriteTexture) {
  53581. this._spriteTexture.dispose();
  53582. this._spriteTexture = null;
  53583. }
  53584. // Remove from scene
  53585. var index = this._scene.spriteManagers.indexOf(this);
  53586. this._scene.spriteManagers.splice(index, 1);
  53587. // Callback
  53588. this.onDisposeObservable.notifyObservers(this);
  53589. this.onDisposeObservable.clear();
  53590. };
  53591. return SpriteManager;
  53592. }());
  53593. BABYLON.SpriteManager = SpriteManager;
  53594. })(BABYLON || (BABYLON = {}));
  53595. //# sourceMappingURL=babylon.spriteManager.js.map
  53596. var BABYLON;
  53597. (function (BABYLON) {
  53598. var Sprite = /** @class */ (function () {
  53599. function Sprite(name, manager) {
  53600. this.name = name;
  53601. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53602. this.width = 1.0;
  53603. this.height = 1.0;
  53604. this.angle = 0;
  53605. this.cellIndex = 0;
  53606. this.invertU = 0;
  53607. this.invertV = 0;
  53608. this.animations = new Array();
  53609. this.isPickable = false;
  53610. this._animationStarted = false;
  53611. this._loopAnimation = false;
  53612. this._fromIndex = 0;
  53613. this._toIndex = 0;
  53614. this._delay = 0;
  53615. this._direction = 1;
  53616. this._time = 0;
  53617. /**
  53618. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53619. */
  53620. this.isVisible = true;
  53621. this._manager = manager;
  53622. this._manager.sprites.push(this);
  53623. this.position = BABYLON.Vector3.Zero();
  53624. }
  53625. Object.defineProperty(Sprite.prototype, "size", {
  53626. get: function () {
  53627. return this.width;
  53628. },
  53629. set: function (value) {
  53630. this.width = value;
  53631. this.height = value;
  53632. },
  53633. enumerable: true,
  53634. configurable: true
  53635. });
  53636. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53637. this._fromIndex = from;
  53638. this._toIndex = to;
  53639. this._loopAnimation = loop;
  53640. this._delay = delay;
  53641. this._animationStarted = true;
  53642. this._direction = from < to ? 1 : -1;
  53643. this.cellIndex = from;
  53644. this._time = 0;
  53645. this._onAnimationEnd = onAnimationEnd;
  53646. };
  53647. Sprite.prototype.stopAnimation = function () {
  53648. this._animationStarted = false;
  53649. };
  53650. Sprite.prototype._animate = function (deltaTime) {
  53651. if (!this._animationStarted)
  53652. return;
  53653. this._time += deltaTime;
  53654. if (this._time > this._delay) {
  53655. this._time = this._time % this._delay;
  53656. this.cellIndex += this._direction;
  53657. if (this.cellIndex > this._toIndex) {
  53658. if (this._loopAnimation) {
  53659. this.cellIndex = this._fromIndex;
  53660. }
  53661. else {
  53662. this.cellIndex = this._toIndex;
  53663. this._animationStarted = false;
  53664. if (this._onAnimationEnd) {
  53665. this._onAnimationEnd();
  53666. }
  53667. if (this.disposeWhenFinishedAnimating) {
  53668. this.dispose();
  53669. }
  53670. }
  53671. }
  53672. }
  53673. };
  53674. Sprite.prototype.dispose = function () {
  53675. for (var i = 0; i < this._manager.sprites.length; i++) {
  53676. if (this._manager.sprites[i] == this) {
  53677. this._manager.sprites.splice(i, 1);
  53678. }
  53679. }
  53680. };
  53681. return Sprite;
  53682. }());
  53683. BABYLON.Sprite = Sprite;
  53684. })(BABYLON || (BABYLON = {}));
  53685. //# sourceMappingURL=babylon.sprite.js.map
  53686. var BABYLON;
  53687. (function (BABYLON) {
  53688. var IntersectionInfo = /** @class */ (function () {
  53689. function IntersectionInfo(bu, bv, distance) {
  53690. this.bu = bu;
  53691. this.bv = bv;
  53692. this.distance = distance;
  53693. this.faceId = 0;
  53694. this.subMeshId = 0;
  53695. }
  53696. return IntersectionInfo;
  53697. }());
  53698. BABYLON.IntersectionInfo = IntersectionInfo;
  53699. /**
  53700. * Information about the result of picking within a scene
  53701. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53702. */
  53703. var PickingInfo = /** @class */ (function () {
  53704. function PickingInfo() {
  53705. /**
  53706. * If the pick collided with an object
  53707. */
  53708. this.hit = false;
  53709. /**
  53710. * Distance away where the pick collided
  53711. */
  53712. this.distance = 0;
  53713. /**
  53714. * The location of pick collision
  53715. */
  53716. this.pickedPoint = null;
  53717. /**
  53718. * The mesh corrisponding the the pick collision
  53719. */
  53720. this.pickedMesh = null;
  53721. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53722. this.bu = 0;
  53723. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53724. this.bv = 0;
  53725. /** The id of the face on the mesh that was picked */
  53726. this.faceId = -1;
  53727. /** Id of the the submesh that was picked */
  53728. this.subMeshId = 0;
  53729. /** If a sprite was picked, this will be the sprite the pick collided with */
  53730. this.pickedSprite = null;
  53731. /**
  53732. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53733. */
  53734. this.originMesh = null;
  53735. /**
  53736. * The ray that was used to perform the picking.
  53737. */
  53738. this.ray = null;
  53739. }
  53740. /**
  53741. * Gets the normal corrispodning to the face the pick collided with
  53742. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53743. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53744. * @returns The normal corrispodning to the face the pick collided with
  53745. */
  53746. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53747. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53748. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53749. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53750. return null;
  53751. }
  53752. var indices = this.pickedMesh.getIndices();
  53753. if (!indices) {
  53754. return null;
  53755. }
  53756. var result;
  53757. if (useVerticesNormals) {
  53758. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53759. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53760. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53761. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53762. normal0 = normal0.scale(this.bu);
  53763. normal1 = normal1.scale(this.bv);
  53764. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53765. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53766. }
  53767. else {
  53768. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53769. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53770. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53771. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53772. var p1p2 = vertex1.subtract(vertex2);
  53773. var p3p2 = vertex3.subtract(vertex2);
  53774. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53775. }
  53776. if (useWorldCoordinates) {
  53777. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  53778. }
  53779. return BABYLON.Vector3.Normalize(result);
  53780. };
  53781. /**
  53782. * Gets the texture coordinates of where the pick occured
  53783. * @returns the vector containing the coordnates of the texture
  53784. */
  53785. PickingInfo.prototype.getTextureCoordinates = function () {
  53786. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53787. return null;
  53788. }
  53789. var indices = this.pickedMesh.getIndices();
  53790. if (!indices) {
  53791. return null;
  53792. }
  53793. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53794. if (!uvs) {
  53795. return null;
  53796. }
  53797. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53798. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53799. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53800. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53801. uv1 = uv1.scale(this.bu);
  53802. uv2 = uv2.scale(this.bv);
  53803. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53804. };
  53805. return PickingInfo;
  53806. }());
  53807. BABYLON.PickingInfo = PickingInfo;
  53808. })(BABYLON || (BABYLON = {}));
  53809. //# sourceMappingURL=babylon.pickingInfo.js.map
  53810. var BABYLON;
  53811. (function (BABYLON) {
  53812. var Ray = /** @class */ (function () {
  53813. function Ray(origin, direction, length) {
  53814. if (length === void 0) { length = Number.MAX_VALUE; }
  53815. this.origin = origin;
  53816. this.direction = direction;
  53817. this.length = length;
  53818. }
  53819. // Methods
  53820. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53821. var d = 0.0;
  53822. var maxValue = Number.MAX_VALUE;
  53823. var inv;
  53824. var min;
  53825. var max;
  53826. var temp;
  53827. if (Math.abs(this.direction.x) < 0.0000001) {
  53828. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53829. return false;
  53830. }
  53831. }
  53832. else {
  53833. inv = 1.0 / this.direction.x;
  53834. min = (minimum.x - this.origin.x) * inv;
  53835. max = (maximum.x - this.origin.x) * inv;
  53836. if (max === -Infinity) {
  53837. max = Infinity;
  53838. }
  53839. if (min > max) {
  53840. temp = min;
  53841. min = max;
  53842. max = temp;
  53843. }
  53844. d = Math.max(min, d);
  53845. maxValue = Math.min(max, maxValue);
  53846. if (d > maxValue) {
  53847. return false;
  53848. }
  53849. }
  53850. if (Math.abs(this.direction.y) < 0.0000001) {
  53851. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53852. return false;
  53853. }
  53854. }
  53855. else {
  53856. inv = 1.0 / this.direction.y;
  53857. min = (minimum.y - this.origin.y) * inv;
  53858. max = (maximum.y - this.origin.y) * inv;
  53859. if (max === -Infinity) {
  53860. max = Infinity;
  53861. }
  53862. if (min > max) {
  53863. temp = min;
  53864. min = max;
  53865. max = temp;
  53866. }
  53867. d = Math.max(min, d);
  53868. maxValue = Math.min(max, maxValue);
  53869. if (d > maxValue) {
  53870. return false;
  53871. }
  53872. }
  53873. if (Math.abs(this.direction.z) < 0.0000001) {
  53874. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53875. return false;
  53876. }
  53877. }
  53878. else {
  53879. inv = 1.0 / this.direction.z;
  53880. min = (minimum.z - this.origin.z) * inv;
  53881. max = (maximum.z - this.origin.z) * inv;
  53882. if (max === -Infinity) {
  53883. max = Infinity;
  53884. }
  53885. if (min > max) {
  53886. temp = min;
  53887. min = max;
  53888. max = temp;
  53889. }
  53890. d = Math.max(min, d);
  53891. maxValue = Math.min(max, maxValue);
  53892. if (d > maxValue) {
  53893. return false;
  53894. }
  53895. }
  53896. return true;
  53897. };
  53898. Ray.prototype.intersectsBox = function (box) {
  53899. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53900. };
  53901. Ray.prototype.intersectsSphere = function (sphere) {
  53902. var x = sphere.center.x - this.origin.x;
  53903. var y = sphere.center.y - this.origin.y;
  53904. var z = sphere.center.z - this.origin.z;
  53905. var pyth = (x * x) + (y * y) + (z * z);
  53906. var rr = sphere.radius * sphere.radius;
  53907. if (pyth <= rr) {
  53908. return true;
  53909. }
  53910. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53911. if (dot < 0.0) {
  53912. return false;
  53913. }
  53914. var temp = pyth - (dot * dot);
  53915. return temp <= rr;
  53916. };
  53917. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53918. if (!this._edge1) {
  53919. this._edge1 = BABYLON.Vector3.Zero();
  53920. this._edge2 = BABYLON.Vector3.Zero();
  53921. this._pvec = BABYLON.Vector3.Zero();
  53922. this._tvec = BABYLON.Vector3.Zero();
  53923. this._qvec = BABYLON.Vector3.Zero();
  53924. }
  53925. vertex1.subtractToRef(vertex0, this._edge1);
  53926. vertex2.subtractToRef(vertex0, this._edge2);
  53927. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53928. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53929. if (det === 0) {
  53930. return null;
  53931. }
  53932. var invdet = 1 / det;
  53933. this.origin.subtractToRef(vertex0, this._tvec);
  53934. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53935. if (bu < 0 || bu > 1.0) {
  53936. return null;
  53937. }
  53938. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53939. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53940. if (bv < 0 || bu + bv > 1.0) {
  53941. return null;
  53942. }
  53943. //check if the distance is longer than the predefined length.
  53944. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53945. if (distance > this.length) {
  53946. return null;
  53947. }
  53948. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53949. };
  53950. Ray.prototype.intersectsPlane = function (plane) {
  53951. var distance;
  53952. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53953. if (Math.abs(result1) < 9.99999997475243E-07) {
  53954. return null;
  53955. }
  53956. else {
  53957. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53958. distance = (-plane.d - result2) / result1;
  53959. if (distance < 0.0) {
  53960. if (distance < -9.99999997475243E-07) {
  53961. return null;
  53962. }
  53963. else {
  53964. return 0;
  53965. }
  53966. }
  53967. return distance;
  53968. }
  53969. };
  53970. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  53971. var tm = BABYLON.Tmp.Matrix[0];
  53972. mesh.getWorldMatrix().invertToRef(tm);
  53973. if (this._tmpRay) {
  53974. Ray.TransformToRef(this, tm, this._tmpRay);
  53975. }
  53976. else {
  53977. this._tmpRay = Ray.Transform(this, tm);
  53978. }
  53979. return mesh.intersects(this._tmpRay, fastCheck);
  53980. };
  53981. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  53982. if (results) {
  53983. results.length = 0;
  53984. }
  53985. else {
  53986. results = [];
  53987. }
  53988. for (var i = 0; i < meshes.length; i++) {
  53989. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  53990. if (pickInfo.hit) {
  53991. results.push(pickInfo);
  53992. }
  53993. }
  53994. results.sort(this._comparePickingInfo);
  53995. return results;
  53996. };
  53997. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  53998. if (pickingInfoA.distance < pickingInfoB.distance) {
  53999. return -1;
  54000. }
  54001. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54002. return 1;
  54003. }
  54004. else {
  54005. return 0;
  54006. }
  54007. };
  54008. /**
  54009. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54010. * @param sega the first point of the segment to test the intersection against
  54011. * @param segb the second point of the segment to test the intersection against
  54012. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54013. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54014. */
  54015. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54016. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54017. var u = segb.subtract(sega);
  54018. var v = rsegb.subtract(this.origin);
  54019. var w = sega.subtract(this.origin);
  54020. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54021. var b = BABYLON.Vector3.Dot(u, v);
  54022. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54023. var d = BABYLON.Vector3.Dot(u, w);
  54024. var e = BABYLON.Vector3.Dot(v, w);
  54025. var D = a * c - b * b; // always >= 0
  54026. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54027. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54028. // compute the line parameters of the two closest points
  54029. if (D < Ray.smallnum) { // the lines are almost parallel
  54030. sN = 0.0; // force using point P0 on segment S1
  54031. sD = 1.0; // to prevent possible division by 0.0 later
  54032. tN = e;
  54033. tD = c;
  54034. }
  54035. else { // get the closest points on the infinite lines
  54036. sN = (b * e - c * d);
  54037. tN = (a * e - b * d);
  54038. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54039. sN = 0.0;
  54040. tN = e;
  54041. tD = c;
  54042. }
  54043. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54044. sN = sD;
  54045. tN = e + b;
  54046. tD = c;
  54047. }
  54048. }
  54049. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54050. tN = 0.0;
  54051. // recompute sc for this edge
  54052. if (-d < 0.0) {
  54053. sN = 0.0;
  54054. }
  54055. else if (-d > a)
  54056. sN = sD;
  54057. else {
  54058. sN = -d;
  54059. sD = a;
  54060. }
  54061. }
  54062. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54063. tN = tD;
  54064. // recompute sc for this edge
  54065. if ((-d + b) < 0.0) {
  54066. sN = 0;
  54067. }
  54068. else if ((-d + b) > a) {
  54069. sN = sD;
  54070. }
  54071. else {
  54072. sN = (-d + b);
  54073. sD = a;
  54074. }
  54075. }
  54076. // finally do the division to get sc and tc
  54077. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54078. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54079. // get the difference of the two closest points
  54080. var qtc = v.multiplyByFloats(tc, tc, tc);
  54081. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54082. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54083. if (isIntersected) {
  54084. return qtc.length();
  54085. }
  54086. return -1;
  54087. };
  54088. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54089. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54090. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54091. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54092. this.direction.normalize();
  54093. return this;
  54094. };
  54095. // Statics
  54096. Ray.Zero = function () {
  54097. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54098. };
  54099. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54100. var result = Ray.Zero();
  54101. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54102. };
  54103. /**
  54104. * 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
  54105. * transformed to the given world matrix.
  54106. * @param origin The origin point
  54107. * @param end The end point
  54108. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54109. */
  54110. Ray.CreateNewFromTo = function (origin, end, world) {
  54111. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54112. var direction = end.subtract(origin);
  54113. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54114. direction.normalize();
  54115. return Ray.Transform(new Ray(origin, direction, length), world);
  54116. };
  54117. Ray.Transform = function (ray, matrix) {
  54118. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54119. Ray.TransformToRef(ray, matrix, result);
  54120. return result;
  54121. };
  54122. Ray.TransformToRef = function (ray, matrix, result) {
  54123. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54124. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54125. result.length = ray.length;
  54126. var dir = result.direction;
  54127. var len = dir.length();
  54128. if (!(len === 0 || len === 1)) {
  54129. var num = 1.0 / len;
  54130. dir.x *= num;
  54131. dir.y *= num;
  54132. dir.z *= num;
  54133. result.length *= len;
  54134. }
  54135. };
  54136. Ray.smallnum = 0.00000001;
  54137. Ray.rayl = 10e8;
  54138. return Ray;
  54139. }());
  54140. BABYLON.Ray = Ray;
  54141. })(BABYLON || (BABYLON = {}));
  54142. //# sourceMappingURL=babylon.ray.js.map
  54143. var BABYLON;
  54144. (function (BABYLON) {
  54145. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54146. if (boxMin.x > sphereCenter.x + sphereRadius)
  54147. return false;
  54148. if (sphereCenter.x - sphereRadius > boxMax.x)
  54149. return false;
  54150. if (boxMin.y > sphereCenter.y + sphereRadius)
  54151. return false;
  54152. if (sphereCenter.y - sphereRadius > boxMax.y)
  54153. return false;
  54154. if (boxMin.z > sphereCenter.z + sphereRadius)
  54155. return false;
  54156. if (sphereCenter.z - sphereRadius > boxMax.z)
  54157. return false;
  54158. return true;
  54159. };
  54160. var getLowestRoot = (function () {
  54161. var result = { root: 0, found: false };
  54162. return function (a, b, c, maxR) {
  54163. result.root = 0;
  54164. result.found = false;
  54165. var determinant = b * b - 4.0 * a * c;
  54166. if (determinant < 0)
  54167. return result;
  54168. var sqrtD = Math.sqrt(determinant);
  54169. var r1 = (-b - sqrtD) / (2.0 * a);
  54170. var r2 = (-b + sqrtD) / (2.0 * a);
  54171. if (r1 > r2) {
  54172. var temp = r2;
  54173. r2 = r1;
  54174. r1 = temp;
  54175. }
  54176. if (r1 > 0 && r1 < maxR) {
  54177. result.root = r1;
  54178. result.found = true;
  54179. return result;
  54180. }
  54181. if (r2 > 0 && r2 < maxR) {
  54182. result.root = r2;
  54183. result.found = true;
  54184. return result;
  54185. }
  54186. return result;
  54187. };
  54188. })();
  54189. var Collider = /** @class */ (function () {
  54190. function Collider() {
  54191. this._collisionPoint = BABYLON.Vector3.Zero();
  54192. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54193. this._tempVector = BABYLON.Vector3.Zero();
  54194. this._tempVector2 = BABYLON.Vector3.Zero();
  54195. this._tempVector3 = BABYLON.Vector3.Zero();
  54196. this._tempVector4 = BABYLON.Vector3.Zero();
  54197. this._edge = BABYLON.Vector3.Zero();
  54198. this._baseToVertex = BABYLON.Vector3.Zero();
  54199. this._destinationPoint = BABYLON.Vector3.Zero();
  54200. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54201. this._displacementVector = BABYLON.Vector3.Zero();
  54202. this._radius = BABYLON.Vector3.One();
  54203. this._retry = 0;
  54204. this._basePointWorld = BABYLON.Vector3.Zero();
  54205. this._velocityWorld = BABYLON.Vector3.Zero();
  54206. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54207. this._collisionMask = -1;
  54208. }
  54209. Object.defineProperty(Collider.prototype, "collisionMask", {
  54210. get: function () {
  54211. return this._collisionMask;
  54212. },
  54213. set: function (mask) {
  54214. this._collisionMask = !isNaN(mask) ? mask : -1;
  54215. },
  54216. enumerable: true,
  54217. configurable: true
  54218. });
  54219. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54220. /**
  54221. * Gets the plane normal used to compute the sliding response (in local space)
  54222. */
  54223. get: function () {
  54224. return this._slidePlaneNormal;
  54225. },
  54226. enumerable: true,
  54227. configurable: true
  54228. });
  54229. // Methods
  54230. Collider.prototype._initialize = function (source, dir, e) {
  54231. this._velocity = dir;
  54232. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54233. this._basePoint = source;
  54234. source.multiplyToRef(this._radius, this._basePointWorld);
  54235. dir.multiplyToRef(this._radius, this._velocityWorld);
  54236. this._velocityWorldLength = this._velocityWorld.length();
  54237. this._epsilon = e;
  54238. this.collisionFound = false;
  54239. };
  54240. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54241. pa.subtractToRef(point, this._tempVector);
  54242. pb.subtractToRef(point, this._tempVector2);
  54243. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54244. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54245. if (d < 0)
  54246. return false;
  54247. pc.subtractToRef(point, this._tempVector3);
  54248. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54249. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54250. if (d < 0)
  54251. return false;
  54252. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54253. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54254. return d >= 0;
  54255. };
  54256. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54257. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54258. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54259. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54260. return false;
  54261. }
  54262. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54263. return false;
  54264. return true;
  54265. };
  54266. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54267. var t0;
  54268. var embeddedInPlane = false;
  54269. //defensive programming, actually not needed.
  54270. if (!trianglePlaneArray) {
  54271. trianglePlaneArray = [];
  54272. }
  54273. if (!trianglePlaneArray[faceIndex]) {
  54274. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54275. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54276. }
  54277. var trianglePlane = trianglePlaneArray[faceIndex];
  54278. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54279. return;
  54280. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54281. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54282. if (normalDotVelocity == 0) {
  54283. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54284. return;
  54285. embeddedInPlane = true;
  54286. t0 = 0;
  54287. }
  54288. else {
  54289. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54290. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54291. if (t0 > t1) {
  54292. var temp = t1;
  54293. t1 = t0;
  54294. t0 = temp;
  54295. }
  54296. if (t0 > 1.0 || t1 < 0.0)
  54297. return;
  54298. if (t0 < 0)
  54299. t0 = 0;
  54300. if (t0 > 1.0)
  54301. t0 = 1.0;
  54302. }
  54303. this._collisionPoint.copyFromFloats(0, 0, 0);
  54304. var found = false;
  54305. var t = 1.0;
  54306. if (!embeddedInPlane) {
  54307. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54308. this._velocity.scaleToRef(t0, this._tempVector);
  54309. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54310. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54311. found = true;
  54312. t = t0;
  54313. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54314. }
  54315. }
  54316. if (!found) {
  54317. var velocitySquaredLength = this._velocity.lengthSquared();
  54318. var a = velocitySquaredLength;
  54319. this._basePoint.subtractToRef(p1, this._tempVector);
  54320. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54321. var c = this._tempVector.lengthSquared() - 1.0;
  54322. var lowestRoot = getLowestRoot(a, b, c, t);
  54323. if (lowestRoot.found) {
  54324. t = lowestRoot.root;
  54325. found = true;
  54326. this._collisionPoint.copyFrom(p1);
  54327. }
  54328. this._basePoint.subtractToRef(p2, this._tempVector);
  54329. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54330. c = this._tempVector.lengthSquared() - 1.0;
  54331. lowestRoot = getLowestRoot(a, b, c, t);
  54332. if (lowestRoot.found) {
  54333. t = lowestRoot.root;
  54334. found = true;
  54335. this._collisionPoint.copyFrom(p2);
  54336. }
  54337. this._basePoint.subtractToRef(p3, this._tempVector);
  54338. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54339. c = this._tempVector.lengthSquared() - 1.0;
  54340. lowestRoot = getLowestRoot(a, b, c, t);
  54341. if (lowestRoot.found) {
  54342. t = lowestRoot.root;
  54343. found = true;
  54344. this._collisionPoint.copyFrom(p3);
  54345. }
  54346. p2.subtractToRef(p1, this._edge);
  54347. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54348. var edgeSquaredLength = this._edge.lengthSquared();
  54349. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54350. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54351. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54352. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54353. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54354. lowestRoot = getLowestRoot(a, b, c, t);
  54355. if (lowestRoot.found) {
  54356. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54357. if (f >= 0.0 && f <= 1.0) {
  54358. t = lowestRoot.root;
  54359. found = true;
  54360. this._edge.scaleInPlace(f);
  54361. p1.addToRef(this._edge, this._collisionPoint);
  54362. }
  54363. }
  54364. p3.subtractToRef(p2, this._edge);
  54365. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54366. edgeSquaredLength = this._edge.lengthSquared();
  54367. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54368. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54369. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54370. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54371. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54372. lowestRoot = getLowestRoot(a, b, c, t);
  54373. if (lowestRoot.found) {
  54374. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54375. if (f >= 0.0 && f <= 1.0) {
  54376. t = lowestRoot.root;
  54377. found = true;
  54378. this._edge.scaleInPlace(f);
  54379. p2.addToRef(this._edge, this._collisionPoint);
  54380. }
  54381. }
  54382. p1.subtractToRef(p3, this._edge);
  54383. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54384. edgeSquaredLength = this._edge.lengthSquared();
  54385. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54386. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54387. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54388. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54389. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54390. lowestRoot = getLowestRoot(a, b, c, t);
  54391. if (lowestRoot.found) {
  54392. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54393. if (f >= 0.0 && f <= 1.0) {
  54394. t = lowestRoot.root;
  54395. found = true;
  54396. this._edge.scaleInPlace(f);
  54397. p3.addToRef(this._edge, this._collisionPoint);
  54398. }
  54399. }
  54400. }
  54401. if (found) {
  54402. var distToCollision = t * this._velocity.length();
  54403. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54404. if (!this.intersectionPoint) {
  54405. this.intersectionPoint = this._collisionPoint.clone();
  54406. }
  54407. else {
  54408. this.intersectionPoint.copyFrom(this._collisionPoint);
  54409. }
  54410. this._nearestDistance = distToCollision;
  54411. this.collisionFound = true;
  54412. }
  54413. }
  54414. };
  54415. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54416. for (var i = indexStart; i < indexEnd; i += 3) {
  54417. var p1 = pts[indices[i] - decal];
  54418. var p2 = pts[indices[i + 1] - decal];
  54419. var p3 = pts[indices[i + 2] - decal];
  54420. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54421. }
  54422. };
  54423. Collider.prototype._getResponse = function (pos, vel) {
  54424. pos.addToRef(vel, this._destinationPoint);
  54425. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54426. this._basePoint.addToRef(vel, pos);
  54427. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54428. this._slidePlaneNormal.normalize();
  54429. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54430. pos.addInPlace(this._displacementVector);
  54431. this.intersectionPoint.addInPlace(this._displacementVector);
  54432. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54433. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54434. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54435. };
  54436. return Collider;
  54437. }());
  54438. BABYLON.Collider = Collider;
  54439. })(BABYLON || (BABYLON = {}));
  54440. //# sourceMappingURL=babylon.collider.js.map
  54441. var BABYLON;
  54442. (function (BABYLON) {
  54443. //WebWorker code will be inserted to this variable.
  54444. BABYLON.CollisionWorker = "";
  54445. /** Defines supported task for worker process */
  54446. var WorkerTaskType;
  54447. (function (WorkerTaskType) {
  54448. /** Initialization */
  54449. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54450. /** Update of geometry */
  54451. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54452. /** Evaluate collision */
  54453. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54454. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54455. /** Defines kind of replies returned by worker */
  54456. var WorkerReplyType;
  54457. (function (WorkerReplyType) {
  54458. /** Success */
  54459. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54460. /** Unkown error */
  54461. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54462. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54463. var CollisionCoordinatorWorker = /** @class */ (function () {
  54464. function CollisionCoordinatorWorker() {
  54465. var _this = this;
  54466. this._scaledPosition = BABYLON.Vector3.Zero();
  54467. this._scaledVelocity = BABYLON.Vector3.Zero();
  54468. this.onMeshUpdated = function (transformNode) {
  54469. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54470. };
  54471. this.onGeometryUpdated = function (geometry) {
  54472. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54473. };
  54474. this._afterRender = function () {
  54475. if (!_this._init)
  54476. return;
  54477. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54478. return;
  54479. }
  54480. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54481. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54482. if (_this._runningUpdated > 4) {
  54483. return;
  54484. }
  54485. ++_this._runningUpdated;
  54486. var payload = {
  54487. updatedMeshes: _this._addUpdateMeshesList,
  54488. updatedGeometries: _this._addUpdateGeometriesList,
  54489. removedGeometries: _this._toRemoveGeometryArray,
  54490. removedMeshes: _this._toRemoveMeshesArray
  54491. };
  54492. var message = {
  54493. payload: payload,
  54494. taskType: WorkerTaskType.UPDATE
  54495. };
  54496. var serializable = [];
  54497. for (var id in payload.updatedGeometries) {
  54498. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54499. //prepare transferables
  54500. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54501. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54502. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54503. }
  54504. }
  54505. _this._worker.postMessage(message, serializable);
  54506. _this._addUpdateMeshesList = {};
  54507. _this._addUpdateGeometriesList = {};
  54508. _this._toRemoveGeometryArray = [];
  54509. _this._toRemoveMeshesArray = [];
  54510. };
  54511. this._onMessageFromWorker = function (e) {
  54512. var returnData = e.data;
  54513. if (returnData.error != WorkerReplyType.SUCCESS) {
  54514. //TODO what errors can be returned from the worker?
  54515. BABYLON.Tools.Warn("error returned from worker!");
  54516. return;
  54517. }
  54518. switch (returnData.taskType) {
  54519. case WorkerTaskType.INIT:
  54520. _this._init = true;
  54521. //Update the worked with ALL of the scene's current state
  54522. _this._scene.meshes.forEach(function (mesh) {
  54523. _this.onMeshAdded(mesh);
  54524. });
  54525. _this._scene.getGeometries().forEach(function (geometry) {
  54526. _this.onGeometryAdded(geometry);
  54527. });
  54528. break;
  54529. case WorkerTaskType.UPDATE:
  54530. _this._runningUpdated--;
  54531. break;
  54532. case WorkerTaskType.COLLIDE:
  54533. var returnPayload = returnData.payload;
  54534. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54535. return;
  54536. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54537. if (callback) {
  54538. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54539. if (mesh) {
  54540. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54541. }
  54542. }
  54543. //cleanup
  54544. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54545. break;
  54546. }
  54547. };
  54548. this._collisionsCallbackArray = [];
  54549. this._init = false;
  54550. this._runningUpdated = 0;
  54551. this._addUpdateMeshesList = {};
  54552. this._addUpdateGeometriesList = {};
  54553. this._toRemoveGeometryArray = [];
  54554. this._toRemoveMeshesArray = [];
  54555. }
  54556. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54557. if (!this._init)
  54558. return;
  54559. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54560. return;
  54561. position.divideToRef(collider._radius, this._scaledPosition);
  54562. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54563. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54564. var payload = {
  54565. collider: {
  54566. position: this._scaledPosition.asArray(),
  54567. velocity: this._scaledVelocity.asArray(),
  54568. radius: collider._radius.asArray()
  54569. },
  54570. collisionId: collisionIndex,
  54571. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54572. maximumRetry: maximumRetry
  54573. };
  54574. var message = {
  54575. payload: payload,
  54576. taskType: WorkerTaskType.COLLIDE
  54577. };
  54578. this._worker.postMessage(message);
  54579. };
  54580. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54581. this._scene = scene;
  54582. this._scene.registerAfterRender(this._afterRender);
  54583. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54584. this._worker = new Worker(workerUrl);
  54585. this._worker.onmessage = this._onMessageFromWorker;
  54586. var message = {
  54587. payload: {},
  54588. taskType: WorkerTaskType.INIT
  54589. };
  54590. this._worker.postMessage(message);
  54591. };
  54592. CollisionCoordinatorWorker.prototype.destroy = function () {
  54593. this._scene.unregisterAfterRender(this._afterRender);
  54594. this._worker.terminate();
  54595. };
  54596. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54597. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54598. this.onMeshUpdated(mesh);
  54599. };
  54600. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54601. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54602. };
  54603. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54604. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54605. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54606. this.onGeometryUpdated(geometry);
  54607. };
  54608. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54609. this._toRemoveGeometryArray.push(geometry.id);
  54610. };
  54611. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54612. var submeshes = [];
  54613. if (mesh.subMeshes) {
  54614. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54615. var boundingInfo = sm.getBoundingInfo();
  54616. return {
  54617. position: idx,
  54618. verticesStart: sm.verticesStart,
  54619. verticesCount: sm.verticesCount,
  54620. indexStart: sm.indexStart,
  54621. indexCount: sm.indexCount,
  54622. hasMaterial: !!sm.getMaterial(),
  54623. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54624. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54625. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54626. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54627. };
  54628. });
  54629. }
  54630. var geometryId = null;
  54631. if (mesh instanceof BABYLON.Mesh) {
  54632. var geometry = mesh.geometry;
  54633. geometryId = geometry ? geometry.id : null;
  54634. }
  54635. else if (mesh instanceof BABYLON.InstancedMesh) {
  54636. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54637. geometryId = geometry ? geometry.id : null;
  54638. }
  54639. var boundingInfo = mesh.getBoundingInfo();
  54640. return {
  54641. uniqueId: mesh.uniqueId,
  54642. id: mesh.id,
  54643. name: mesh.name,
  54644. geometryId: geometryId,
  54645. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54646. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54647. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54648. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54649. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54650. subMeshes: submeshes,
  54651. checkCollisions: mesh.checkCollisions
  54652. };
  54653. };
  54654. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54655. return {
  54656. id: geometry.id,
  54657. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54658. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54659. indices: new Uint32Array(geometry.getIndices() || []),
  54660. };
  54661. };
  54662. return CollisionCoordinatorWorker;
  54663. }());
  54664. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54665. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54666. function CollisionCoordinatorLegacy() {
  54667. this._scaledPosition = BABYLON.Vector3.Zero();
  54668. this._scaledVelocity = BABYLON.Vector3.Zero();
  54669. this._finalPosition = BABYLON.Vector3.Zero();
  54670. }
  54671. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54672. position.divideToRef(collider._radius, this._scaledPosition);
  54673. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54674. collider.collidedMesh = null;
  54675. collider._retry = 0;
  54676. collider._initialVelocity = this._scaledVelocity;
  54677. collider._initialPosition = this._scaledPosition;
  54678. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54679. this._finalPosition.multiplyInPlace(collider._radius);
  54680. //run the callback
  54681. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54682. };
  54683. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54684. this._scene = scene;
  54685. };
  54686. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54687. //Legacy need no destruction method.
  54688. };
  54689. //No update in legacy mode
  54690. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54691. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54692. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54693. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54694. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54695. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54696. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54697. if (excludedMesh === void 0) { excludedMesh = null; }
  54698. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54699. if (collider._retry >= maximumRetry) {
  54700. finalPosition.copyFrom(position);
  54701. return;
  54702. }
  54703. // Check if this is a mesh else camera or -1
  54704. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54705. collider._initialize(position, velocity, closeDistance);
  54706. // Check all meshes
  54707. for (var index = 0; index < this._scene.meshes.length; index++) {
  54708. var mesh = this._scene.meshes[index];
  54709. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54710. mesh._checkCollision(collider);
  54711. }
  54712. }
  54713. if (!collider.collisionFound) {
  54714. position.addToRef(velocity, finalPosition);
  54715. return;
  54716. }
  54717. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54718. collider._getResponse(position, velocity);
  54719. }
  54720. if (velocity.length() <= closeDistance) {
  54721. finalPosition.copyFrom(position);
  54722. return;
  54723. }
  54724. collider._retry++;
  54725. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54726. };
  54727. return CollisionCoordinatorLegacy;
  54728. }());
  54729. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54730. })(BABYLON || (BABYLON = {}));
  54731. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54732. var BABYLON;
  54733. (function (BABYLON) {
  54734. /**
  54735. * A particle represents one of the element emitted by a particle system.
  54736. * This is mainly define by its coordinates, direction, velocity and age.
  54737. */
  54738. var Particle = /** @class */ (function () {
  54739. /**
  54740. * Creates a new instance Particle
  54741. * @param particleSystem the particle system the particle belongs to
  54742. */
  54743. function Particle(
  54744. /**
  54745. * particleSystem the particle system the particle belongs to.
  54746. */
  54747. particleSystem) {
  54748. this.particleSystem = particleSystem;
  54749. /**
  54750. * The world position of the particle in the scene.
  54751. */
  54752. this.position = BABYLON.Vector3.Zero();
  54753. /**
  54754. * The world direction of the particle in the scene.
  54755. */
  54756. this.direction = BABYLON.Vector3.Zero();
  54757. /**
  54758. * The color of the particle.
  54759. */
  54760. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54761. /**
  54762. * The color change of the particle per step.
  54763. */
  54764. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54765. /**
  54766. * Defines how long will the life of the particle be.
  54767. */
  54768. this.lifeTime = 1.0;
  54769. /**
  54770. * The current age of the particle.
  54771. */
  54772. this.age = 0;
  54773. /**
  54774. * The current size of the particle.
  54775. */
  54776. this.size = 0;
  54777. /**
  54778. * The current scale of the particle.
  54779. */
  54780. this.scale = new BABYLON.Vector2(1, 1);
  54781. /**
  54782. * The current angle of the particle.
  54783. */
  54784. this.angle = 0;
  54785. /**
  54786. * Defines how fast is the angle changing.
  54787. */
  54788. this.angularSpeed = 0;
  54789. /**
  54790. * Defines the cell index used by the particle to be rendered from a sprite.
  54791. */
  54792. this.cellIndex = 0;
  54793. this._currentFrameCounter = 0;
  54794. if (!this.particleSystem.isAnimationSheetEnabled) {
  54795. return;
  54796. }
  54797. this.updateCellInfoFromSystem();
  54798. }
  54799. Particle.prototype.updateCellInfoFromSystem = function () {
  54800. this.cellIndex = this.particleSystem.startSpriteCellID;
  54801. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  54802. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  54803. }
  54804. else {
  54805. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  54806. }
  54807. };
  54808. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  54809. // (ageOffset / scaledUpdateSpeed) / available cells
  54810. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  54811. this._currentFrameCounter += scaledUpdateSpeed;
  54812. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  54813. this._currentFrameCounter = 0;
  54814. this.cellIndex++;
  54815. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54816. this.cellIndex = this.particleSystem.endSpriteCellID;
  54817. }
  54818. }
  54819. };
  54820. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  54821. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  54822. this.cellIndex++;
  54823. this._currentFrameCounter = 0;
  54824. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54825. if (this.particleSystem.spriteCellLoop) {
  54826. this.cellIndex = this.particleSystem.startSpriteCellID;
  54827. }
  54828. else {
  54829. this.cellIndex = this.particleSystem.endSpriteCellID;
  54830. }
  54831. }
  54832. }
  54833. else {
  54834. this._currentFrameCounter++;
  54835. }
  54836. };
  54837. /**
  54838. * Copy the properties of particle to another one.
  54839. * @param other the particle to copy the information to.
  54840. */
  54841. Particle.prototype.copyTo = function (other) {
  54842. other.position.copyFrom(this.position);
  54843. if (this._initialDirection) {
  54844. if (other._initialDirection) {
  54845. other._initialDirection.copyFrom(this._initialDirection);
  54846. }
  54847. else {
  54848. other._initialDirection = this._initialDirection.clone();
  54849. }
  54850. }
  54851. else {
  54852. other._initialDirection = null;
  54853. }
  54854. other.direction.copyFrom(this.direction);
  54855. other.color.copyFrom(this.color);
  54856. other.colorStep.copyFrom(this.colorStep);
  54857. other.lifeTime = this.lifeTime;
  54858. other.age = this.age;
  54859. other.size = this.size;
  54860. other.scale.copyFrom(this.scale);
  54861. other.angle = this.angle;
  54862. other.angularSpeed = this.angularSpeed;
  54863. other.particleSystem = this.particleSystem;
  54864. other.cellIndex = this.cellIndex;
  54865. };
  54866. return Particle;
  54867. }());
  54868. BABYLON.Particle = Particle;
  54869. })(BABYLON || (BABYLON = {}));
  54870. //# sourceMappingURL=babylon.particle.js.map
  54871. var BABYLON;
  54872. (function (BABYLON) {
  54873. /**
  54874. * This represents a particle system in Babylon.
  54875. * 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.
  54876. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54877. * @example https://doc.babylonjs.com/babylon101/particles
  54878. */
  54879. var ParticleSystem = /** @class */ (function () {
  54880. /**
  54881. * Instantiates a particle system.
  54882. * 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.
  54883. * @param name The name of the particle system
  54884. * @param capacity The max number of particles alive at the same time
  54885. * @param scene The scene the particle system belongs to
  54886. * @param customEffect a custom effect used to change the way particles are rendered by default
  54887. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54888. * @param epsilon Offset used to render the particles
  54889. */
  54890. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54891. if (customEffect === void 0) { customEffect = null; }
  54892. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54893. if (epsilon === void 0) { epsilon = 0.01; }
  54894. var _this = this;
  54895. /**
  54896. * List of animations used by the particle system.
  54897. */
  54898. this.animations = [];
  54899. /**
  54900. * The rendering group used by the Particle system to chose when to render.
  54901. */
  54902. this.renderingGroupId = 0;
  54903. /**
  54904. * The emitter represents the Mesh or position we are attaching the particle system to.
  54905. */
  54906. this.emitter = null;
  54907. /**
  54908. * The maximum number of particles to emit per frame
  54909. */
  54910. this.emitRate = 10;
  54911. /**
  54912. * If you want to launch only a few particles at once, that can be done, as well.
  54913. */
  54914. this.manualEmitCount = -1;
  54915. /**
  54916. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54917. */
  54918. this.updateSpeed = 0.01;
  54919. /**
  54920. * The amount of time the particle system is running (depends of the overall update speed).
  54921. */
  54922. this.targetStopDuration = 0;
  54923. /**
  54924. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54925. */
  54926. this.disposeOnStop = false;
  54927. /**
  54928. * Minimum power of emitting particles.
  54929. */
  54930. this.minEmitPower = 1;
  54931. /**
  54932. * Maximum power of emitting particles.
  54933. */
  54934. this.maxEmitPower = 1;
  54935. /**
  54936. * Minimum life time of emitting particles.
  54937. */
  54938. this.minLifeTime = 1;
  54939. /**
  54940. * Maximum life time of emitting particles.
  54941. */
  54942. this.maxLifeTime = 1;
  54943. /**
  54944. * Minimum Size of emitting particles.
  54945. */
  54946. this.minSize = 1;
  54947. /**
  54948. * Maximum Size of emitting particles.
  54949. */
  54950. this.maxSize = 1;
  54951. /**
  54952. * Minimum scale of emitting particles on X axis.
  54953. */
  54954. this.minScaleX = 1;
  54955. /**
  54956. * Maximum scale of emitting particles on X axis.
  54957. */
  54958. this.maxScaleX = 1;
  54959. /**
  54960. * Minimum scale of emitting particles on Y axis.
  54961. */
  54962. this.minScaleY = 1;
  54963. /**
  54964. * Maximum scale of emitting particles on Y axis.
  54965. */
  54966. this.maxScaleY = 1;
  54967. /**
  54968. * Gets or sets the minimal initial rotation in radians.
  54969. */
  54970. this.minInitialRotation = 0;
  54971. /**
  54972. * Gets or sets the maximal initial rotation in radians.
  54973. */
  54974. this.maxInitialRotation = 0;
  54975. /**
  54976. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  54977. */
  54978. this.minAngularSpeed = 0;
  54979. /**
  54980. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  54981. */
  54982. this.maxAngularSpeed = 0;
  54983. /**
  54984. * The layer mask we are rendering the particles through.
  54985. */
  54986. this.layerMask = 0x0FFFFFFF;
  54987. /**
  54988. * This can help using your own shader to render the particle system.
  54989. * The according effect will be created
  54990. */
  54991. this.customShader = null;
  54992. /**
  54993. * By default particle system starts as soon as they are created. This prevents the
  54994. * automatic start to happen and let you decide when to start emitting particles.
  54995. */
  54996. this.preventAutoStart = false;
  54997. /**
  54998. * Callback triggered when the particle animation is ending.
  54999. */
  55000. this.onAnimationEnd = null;
  55001. /**
  55002. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55003. */
  55004. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55005. /**
  55006. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55007. * to override the particles.
  55008. */
  55009. this.forceDepthWrite = false;
  55010. /**
  55011. * You can use gravity if you want to give an orientation to your particles.
  55012. */
  55013. this.gravity = BABYLON.Vector3.Zero();
  55014. this._colorGradients = null;
  55015. this._sizeGradients = null;
  55016. /**
  55017. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55018. */
  55019. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55020. /**
  55021. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55022. */
  55023. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55024. /**
  55025. * Color the particle will have at the end of its lifetime
  55026. */
  55027. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55028. /**
  55029. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55030. */
  55031. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55032. /**
  55033. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not
  55034. */
  55035. this.spriteCellLoop = true;
  55036. /**
  55037. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop
  55038. */
  55039. this.spriteCellChangeSpeed = 0;
  55040. /**
  55041. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display
  55042. */
  55043. this.startSpriteCellID = 0;
  55044. /**
  55045. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display
  55046. */
  55047. this.endSpriteCellID = 0;
  55048. /**
  55049. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55050. */
  55051. this.spriteCellWidth = 0;
  55052. /**
  55053. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55054. */
  55055. this.spriteCellHeight = 0;
  55056. /** 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 */
  55057. this.preWarmCycles = 0;
  55058. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55059. this.preWarmStepOffset = 1;
  55060. /**
  55061. * An event triggered when the system is disposed
  55062. */
  55063. this.onDisposeObservable = new BABYLON.Observable();
  55064. this._particles = new Array();
  55065. this._stockParticles = new Array();
  55066. this._newPartsExcess = 0;
  55067. this._vertexBuffers = {};
  55068. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55069. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55070. this._scaledDirection = BABYLON.Vector3.Zero();
  55071. this._scaledGravity = BABYLON.Vector3.Zero();
  55072. this._currentRenderId = -1;
  55073. this._useInstancing = false;
  55074. this._started = false;
  55075. this._stopped = false;
  55076. this._actualFrame = 0;
  55077. this._isBillboardBased = true;
  55078. // start of sub system methods
  55079. /**
  55080. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55081. * Its lifetime will start back at 0.
  55082. */
  55083. this.recycleParticle = function (particle) {
  55084. var lastParticle = _this._particles.pop();
  55085. if (lastParticle !== particle) {
  55086. lastParticle.copyTo(particle);
  55087. }
  55088. _this._stockParticles.push(lastParticle);
  55089. };
  55090. this._createParticle = function () {
  55091. var particle;
  55092. if (_this._stockParticles.length !== 0) {
  55093. particle = _this._stockParticles.pop();
  55094. particle.age = 0;
  55095. particle.cellIndex = _this.startSpriteCellID;
  55096. }
  55097. else {
  55098. particle = new BABYLON.Particle(_this);
  55099. }
  55100. return particle;
  55101. };
  55102. this._emitFromParticle = function (particle) {
  55103. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55104. return;
  55105. }
  55106. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55107. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55108. subSystem._rootParticleSystem = _this;
  55109. _this.activeSubSystems.push(subSystem);
  55110. subSystem.start();
  55111. };
  55112. this.id = name;
  55113. this.name = name;
  55114. this._capacity = capacity;
  55115. this._epsilon = epsilon;
  55116. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55117. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55118. this._customEffect = customEffect;
  55119. scene.particleSystems.push(this);
  55120. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  55121. this._createIndexBuffer();
  55122. this._createVertexBuffers();
  55123. // Default emitter type
  55124. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55125. this.updateFunction = function (particles) {
  55126. for (var index = 0; index < particles.length; index++) {
  55127. var particle = particles[index];
  55128. particle.age += _this._scaledUpdateSpeed;
  55129. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55130. _this._emitFromParticle(particle);
  55131. _this.recycleParticle(particle);
  55132. index--;
  55133. continue;
  55134. }
  55135. else {
  55136. var ratio = particle.age / particle.lifeTime;
  55137. // Color
  55138. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55139. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55140. BABYLON.Color4.LerpToRef(currentGradient.color, nextGradient.color, scale, particle.color);
  55141. });
  55142. }
  55143. else {
  55144. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55145. particle.color.addInPlace(_this._scaledColorStep);
  55146. if (particle.color.a < 0) {
  55147. particle.color.a = 0;
  55148. }
  55149. }
  55150. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55151. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55152. particle.position.addInPlace(_this._scaledDirection);
  55153. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55154. particle.direction.addInPlace(_this._scaledGravity);
  55155. // Gradient
  55156. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55157. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55158. particle.size = particle._initialSize * BABYLON.Scalar.Lerp(currentGradient.factor, nextGradient.factor, scale);
  55159. });
  55160. }
  55161. if (_this._isAnimationSheetEnabled) {
  55162. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55163. }
  55164. }
  55165. }
  55166. };
  55167. }
  55168. /**
  55169. * Gets the current list of color gradients.
  55170. * You must use addColorGradient and removeColorGradient to udpate this list
  55171. * @returns the list of color gradients
  55172. */
  55173. ParticleSystem.prototype.getColorGradients = function () {
  55174. return this._colorGradients;
  55175. };
  55176. /**
  55177. * Gets the current list of size gradients.
  55178. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55179. * @returns the list of size gradients
  55180. */
  55181. ParticleSystem.prototype.getSizeGradients = function () {
  55182. return this._sizeGradients;
  55183. };
  55184. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55185. /**
  55186. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55187. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55188. */
  55189. get: function () {
  55190. if (this.particleEmitterType.direction1) {
  55191. return this.particleEmitterType.direction1;
  55192. }
  55193. return BABYLON.Vector3.Zero();
  55194. },
  55195. set: function (value) {
  55196. if (this.particleEmitterType.direction1) {
  55197. this.particleEmitterType.direction1 = value;
  55198. }
  55199. },
  55200. enumerable: true,
  55201. configurable: true
  55202. });
  55203. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55204. /**
  55205. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55206. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55207. */
  55208. get: function () {
  55209. if (this.particleEmitterType.direction2) {
  55210. return this.particleEmitterType.direction2;
  55211. }
  55212. return BABYLON.Vector3.Zero();
  55213. },
  55214. set: function (value) {
  55215. if (this.particleEmitterType.direction2) {
  55216. this.particleEmitterType.direction2 = value;
  55217. }
  55218. },
  55219. enumerable: true,
  55220. configurable: true
  55221. });
  55222. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55223. /**
  55224. * 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.
  55225. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55226. */
  55227. get: function () {
  55228. if (this.particleEmitterType.minEmitBox) {
  55229. return this.particleEmitterType.minEmitBox;
  55230. }
  55231. return BABYLON.Vector3.Zero();
  55232. },
  55233. set: function (value) {
  55234. if (this.particleEmitterType.minEmitBox) {
  55235. this.particleEmitterType.minEmitBox = value;
  55236. }
  55237. },
  55238. enumerable: true,
  55239. configurable: true
  55240. });
  55241. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55242. /**
  55243. * 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.
  55244. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55245. */
  55246. get: function () {
  55247. if (this.particleEmitterType.maxEmitBox) {
  55248. return this.particleEmitterType.maxEmitBox;
  55249. }
  55250. return BABYLON.Vector3.Zero();
  55251. },
  55252. set: function (value) {
  55253. if (this.particleEmitterType.maxEmitBox) {
  55254. this.particleEmitterType.maxEmitBox = value;
  55255. }
  55256. },
  55257. enumerable: true,
  55258. configurable: true
  55259. });
  55260. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55261. /**
  55262. * Sets a callback that will be triggered when the system is disposed
  55263. */
  55264. set: function (callback) {
  55265. if (this._onDisposeObserver) {
  55266. this.onDisposeObservable.remove(this._onDisposeObserver);
  55267. }
  55268. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55269. },
  55270. enumerable: true,
  55271. configurable: true
  55272. });
  55273. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55274. /**
  55275. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55276. */
  55277. get: function () {
  55278. return this._isAnimationSheetEnabled;
  55279. },
  55280. enumerable: true,
  55281. configurable: true
  55282. });
  55283. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55284. /**
  55285. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55286. */
  55287. get: function () {
  55288. return this._isBillboardBased;
  55289. },
  55290. set: function (value) {
  55291. if (this._isBillboardBased === value) {
  55292. return;
  55293. }
  55294. this._isBillboardBased = value;
  55295. this._resetEffect();
  55296. },
  55297. enumerable: true,
  55298. configurable: true
  55299. });
  55300. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55301. //end of Sub-emitter
  55302. /**
  55303. * Gets the current list of active particles
  55304. */
  55305. get: function () {
  55306. return this._particles;
  55307. },
  55308. enumerable: true,
  55309. configurable: true
  55310. });
  55311. /**
  55312. * Returns the string "ParticleSystem"
  55313. * @returns a string containing the class name
  55314. */
  55315. ParticleSystem.prototype.getClassName = function () {
  55316. return "ParticleSystem";
  55317. };
  55318. /**
  55319. * Adds a new size gradient
  55320. * @param gradient defines the gradient to use (between 0 and 1)
  55321. * @param factor defines the size factor to affect to the specified gradient
  55322. */
  55323. ParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  55324. if (!this._sizeGradients) {
  55325. this._sizeGradients = [];
  55326. }
  55327. var sizeGradient = new BABYLON.FactorGradient();
  55328. sizeGradient.gradient = gradient;
  55329. sizeGradient.factor = factor;
  55330. this._sizeGradients.push(sizeGradient);
  55331. this._sizeGradients.sort(function (a, b) {
  55332. if (a.gradient < b.gradient) {
  55333. return -1;
  55334. }
  55335. else if (a.gradient > b.gradient) {
  55336. return 1;
  55337. }
  55338. return 0;
  55339. });
  55340. return this;
  55341. };
  55342. /**
  55343. * Remove a specific size gradient
  55344. * @param gradient defines the gradient to remove
  55345. */
  55346. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55347. if (!this._sizeGradients) {
  55348. return this;
  55349. }
  55350. var index = 0;
  55351. for (var _i = 0, _a = this._sizeGradients; _i < _a.length; _i++) {
  55352. var sizeGradient = _a[_i];
  55353. if (sizeGradient.gradient === gradient) {
  55354. this._sizeGradients.splice(index, 1);
  55355. break;
  55356. }
  55357. index++;
  55358. }
  55359. return this;
  55360. };
  55361. /**
  55362. * Adds a new color gradient
  55363. * @param gradient defines the gradient to use (between 0 and 1)
  55364. * @param color defines the color to affect to the specified gradient
  55365. */
  55366. ParticleSystem.prototype.addColorGradient = function (gradient, color) {
  55367. if (!this._colorGradients) {
  55368. this._colorGradients = [];
  55369. }
  55370. var colorGradient = new BABYLON.ColorGradient();
  55371. colorGradient.gradient = gradient;
  55372. colorGradient.color = color;
  55373. this._colorGradients.push(colorGradient);
  55374. this._colorGradients.sort(function (a, b) {
  55375. if (a.gradient < b.gradient) {
  55376. return -1;
  55377. }
  55378. else if (a.gradient > b.gradient) {
  55379. return 1;
  55380. }
  55381. return 0;
  55382. });
  55383. return this;
  55384. };
  55385. /**
  55386. * Remove a specific color gradient
  55387. * @param gradient defines the gradient to remove
  55388. */
  55389. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55390. if (!this._colorGradients) {
  55391. return this;
  55392. }
  55393. var index = 0;
  55394. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55395. var colorGradient = _a[_i];
  55396. if (colorGradient.gradient === gradient) {
  55397. this._colorGradients.splice(index, 1);
  55398. break;
  55399. }
  55400. index++;
  55401. }
  55402. return this;
  55403. };
  55404. ParticleSystem.prototype._resetEffect = function () {
  55405. if (this._vertexBuffer) {
  55406. this._vertexBuffer.dispose();
  55407. this._vertexBuffer = null;
  55408. }
  55409. if (this._spriteBuffer) {
  55410. this._spriteBuffer.dispose();
  55411. this._spriteBuffer = null;
  55412. }
  55413. this._createVertexBuffers();
  55414. };
  55415. ParticleSystem.prototype._createVertexBuffers = function () {
  55416. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55417. if (this._isAnimationSheetEnabled) {
  55418. this._vertexBufferSize += 1;
  55419. }
  55420. if (!this._isBillboardBased) {
  55421. this._vertexBufferSize += 3;
  55422. }
  55423. var engine = this._scene.getEngine();
  55424. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55425. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55426. var dataOffset = 0;
  55427. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55428. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55429. dataOffset += 3;
  55430. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55431. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55432. dataOffset += 4;
  55433. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55434. this._vertexBuffers["angle"] = options;
  55435. dataOffset += 1;
  55436. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55437. this._vertexBuffers["size"] = size;
  55438. dataOffset += 2;
  55439. if (this._isAnimationSheetEnabled) {
  55440. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55441. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55442. dataOffset += 1;
  55443. }
  55444. if (!this._isBillboardBased) {
  55445. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55446. this._vertexBuffers["direction"] = directionBuffer;
  55447. dataOffset += 3;
  55448. }
  55449. var offsets;
  55450. if (this._useInstancing) {
  55451. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55452. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55453. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55454. }
  55455. else {
  55456. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55457. dataOffset += 2;
  55458. }
  55459. this._vertexBuffers["offset"] = offsets;
  55460. };
  55461. ParticleSystem.prototype._createIndexBuffer = function () {
  55462. if (this._useInstancing) {
  55463. return;
  55464. }
  55465. var indices = [];
  55466. var index = 0;
  55467. for (var count = 0; count < this._capacity; count++) {
  55468. indices.push(index);
  55469. indices.push(index + 1);
  55470. indices.push(index + 2);
  55471. indices.push(index);
  55472. indices.push(index + 2);
  55473. indices.push(index + 3);
  55474. index += 4;
  55475. }
  55476. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55477. };
  55478. /**
  55479. * Gets the maximum number of particles active at the same time.
  55480. * @returns The max number of active particles.
  55481. */
  55482. ParticleSystem.prototype.getCapacity = function () {
  55483. return this._capacity;
  55484. };
  55485. /**
  55486. * Gets Wether there are still active particles in the system.
  55487. * @returns True if it is alive, otherwise false.
  55488. */
  55489. ParticleSystem.prototype.isAlive = function () {
  55490. return this._alive;
  55491. };
  55492. /**
  55493. * Gets Wether the system has been started.
  55494. * @returns True if it has been started, otherwise false.
  55495. */
  55496. ParticleSystem.prototype.isStarted = function () {
  55497. return this._started;
  55498. };
  55499. /**
  55500. * Starts the particle system and begins to emit.
  55501. */
  55502. ParticleSystem.prototype.start = function () {
  55503. this._started = true;
  55504. this._stopped = false;
  55505. this._actualFrame = 0;
  55506. if (this.subEmitters && this.subEmitters.length != 0) {
  55507. this.activeSubSystems = new Array();
  55508. }
  55509. if (this.preWarmCycles) {
  55510. for (var index = 0; index < this.preWarmCycles; index++) {
  55511. this.animate(true);
  55512. }
  55513. }
  55514. };
  55515. /**
  55516. * Stops the particle system.
  55517. * @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.
  55518. */
  55519. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55520. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55521. this._stopped = true;
  55522. if (stopSubEmitters) {
  55523. this._stopSubEmitters();
  55524. }
  55525. };
  55526. // animation sheet
  55527. /**
  55528. * Remove all active particles
  55529. */
  55530. ParticleSystem.prototype.reset = function () {
  55531. this._stockParticles = [];
  55532. this._particles = [];
  55533. };
  55534. /**
  55535. * @hidden (for internal use only)
  55536. */
  55537. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55538. var offset = index * this._vertexBufferSize;
  55539. this._vertexData[offset++] = particle.position.x;
  55540. this._vertexData[offset++] = particle.position.y;
  55541. this._vertexData[offset++] = particle.position.z;
  55542. this._vertexData[offset++] = particle.color.r;
  55543. this._vertexData[offset++] = particle.color.g;
  55544. this._vertexData[offset++] = particle.color.b;
  55545. this._vertexData[offset++] = particle.color.a;
  55546. this._vertexData[offset++] = particle.angle;
  55547. this._vertexData[offset++] = particle.scale.x * particle.size;
  55548. this._vertexData[offset++] = particle.scale.y * particle.size;
  55549. if (this._isAnimationSheetEnabled) {
  55550. this._vertexData[offset++] = particle.cellIndex;
  55551. }
  55552. if (!this._isBillboardBased) {
  55553. if (particle._initialDirection) {
  55554. this._vertexData[offset++] = particle._initialDirection.x;
  55555. this._vertexData[offset++] = particle._initialDirection.y;
  55556. this._vertexData[offset++] = particle._initialDirection.z;
  55557. }
  55558. else {
  55559. this._vertexData[offset++] = particle.direction.x;
  55560. this._vertexData[offset++] = particle.direction.y;
  55561. this._vertexData[offset++] = particle.direction.z;
  55562. }
  55563. }
  55564. if (!this._useInstancing) {
  55565. if (this._isAnimationSheetEnabled) {
  55566. if (offsetX === 0)
  55567. offsetX = this._epsilon;
  55568. else if (offsetX === 1)
  55569. offsetX = 1 - this._epsilon;
  55570. if (offsetY === 0)
  55571. offsetY = this._epsilon;
  55572. else if (offsetY === 1)
  55573. offsetY = 1 - this._epsilon;
  55574. }
  55575. this._vertexData[offset++] = offsetX;
  55576. this._vertexData[offset++] = offsetY;
  55577. }
  55578. };
  55579. ParticleSystem.prototype._stopSubEmitters = function () {
  55580. if (!this.activeSubSystems) {
  55581. return;
  55582. }
  55583. this.activeSubSystems.forEach(function (subSystem) {
  55584. subSystem.stop(true);
  55585. });
  55586. this.activeSubSystems = new Array();
  55587. };
  55588. ParticleSystem.prototype._removeFromRoot = function () {
  55589. if (!this._rootParticleSystem) {
  55590. return;
  55591. }
  55592. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55593. if (index !== -1) {
  55594. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55595. }
  55596. };
  55597. // end of sub system methods
  55598. ParticleSystem.prototype._update = function (newParticles) {
  55599. // Update current
  55600. this._alive = this._particles.length > 0;
  55601. this.updateFunction(this._particles);
  55602. // Add new ones
  55603. var worldMatrix;
  55604. if (this.emitter.position) {
  55605. var emitterMesh = this.emitter;
  55606. worldMatrix = emitterMesh.getWorldMatrix();
  55607. }
  55608. else {
  55609. var emitterPosition = this.emitter;
  55610. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55611. }
  55612. var particle;
  55613. for (var index = 0; index < newParticles; index++) {
  55614. if (this._particles.length === this._capacity) {
  55615. break;
  55616. }
  55617. particle = this._createParticle();
  55618. this._particles.push(particle);
  55619. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  55620. if (this.startPositionFunction) {
  55621. this.startPositionFunction(worldMatrix, particle.position, particle);
  55622. }
  55623. else {
  55624. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55625. }
  55626. if (this.startDirectionFunction) {
  55627. this.startDirectionFunction(worldMatrix, particle.direction, particle);
  55628. }
  55629. else {
  55630. this.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  55631. }
  55632. if (emitPower === 0) {
  55633. if (!particle._initialDirection) {
  55634. particle._initialDirection = particle.direction.clone();
  55635. }
  55636. else {
  55637. particle._initialDirection.copyFrom(particle.direction);
  55638. }
  55639. }
  55640. else {
  55641. particle._initialDirection = null;
  55642. }
  55643. particle.direction.scaleInPlace(emitPower);
  55644. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  55645. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  55646. particle._initialSize = particle.size;
  55647. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this.minScaleX, this.maxScaleX), BABYLON.Scalar.RandomRange(this.minScaleY, this.maxScaleY));
  55648. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  55649. particle.angle = BABYLON.Scalar.RandomRange(this.minInitialRotation, this.maxInitialRotation);
  55650. if (!this._colorGradients || this._colorGradients.length === 0) {
  55651. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  55652. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  55653. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  55654. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55655. }
  55656. else {
  55657. particle.color.copyFrom(this._colorGradients[0].color);
  55658. }
  55659. }
  55660. };
  55661. ParticleSystem.prototype._getEffect = function () {
  55662. if (this._customEffect) {
  55663. return this._customEffect;
  55664. }
  55665. ;
  55666. var defines = [];
  55667. if (this._scene.clipPlane) {
  55668. defines.push("#define CLIPPLANE");
  55669. }
  55670. if (this._isAnimationSheetEnabled) {
  55671. defines.push("#define ANIMATESHEET");
  55672. }
  55673. if (this._isBillboardBased) {
  55674. defines.push("#define BILLBOARD");
  55675. }
  55676. // Effect
  55677. var join = defines.join("\n");
  55678. if (this._cachedDefines !== join) {
  55679. this._cachedDefines = join;
  55680. var attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55681. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  55682. if (this._isAnimationSheetEnabled) {
  55683. attributesNamesOrOptions.push("cellIndex");
  55684. effectCreationOption.push("particlesInfos");
  55685. }
  55686. if (!this._isBillboardBased) {
  55687. attributesNamesOrOptions.push("direction");
  55688. }
  55689. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55690. }
  55691. return this._effect;
  55692. };
  55693. /**
  55694. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55695. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  55696. */
  55697. ParticleSystem.prototype.animate = function (preWarmOnly) {
  55698. if (preWarmOnly === void 0) { preWarmOnly = false; }
  55699. if (!this._started)
  55700. return;
  55701. if (!preWarmOnly) {
  55702. var effect = this._getEffect();
  55703. // Check
  55704. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55705. return;
  55706. if (this._currentRenderId === this._scene.getRenderId()) {
  55707. return;
  55708. }
  55709. this._currentRenderId = this._scene.getRenderId();
  55710. }
  55711. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  55712. // determine the number of particles we need to create
  55713. var newParticles;
  55714. if (this.manualEmitCount > -1) {
  55715. newParticles = this.manualEmitCount;
  55716. this._newPartsExcess = 0;
  55717. this.manualEmitCount = 0;
  55718. }
  55719. else {
  55720. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55721. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55722. }
  55723. if (this._newPartsExcess > 1.0) {
  55724. newParticles += this._newPartsExcess >> 0;
  55725. this._newPartsExcess -= this._newPartsExcess >> 0;
  55726. }
  55727. this._alive = false;
  55728. if (!this._stopped) {
  55729. this._actualFrame += this._scaledUpdateSpeed;
  55730. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55731. this.stop();
  55732. }
  55733. else {
  55734. newParticles = 0;
  55735. }
  55736. this._update(newParticles);
  55737. // Stopped?
  55738. if (this._stopped) {
  55739. if (!this._alive) {
  55740. this._started = false;
  55741. if (this.onAnimationEnd) {
  55742. this.onAnimationEnd();
  55743. }
  55744. if (this.disposeOnStop) {
  55745. this._scene._toBeDisposed.push(this);
  55746. }
  55747. }
  55748. }
  55749. if (!preWarmOnly) {
  55750. // Update VBO
  55751. var offset = 0;
  55752. for (var index = 0; index < this._particles.length; index++) {
  55753. var particle = this._particles[index];
  55754. this._appendParticleVertices(offset, particle);
  55755. offset += this._useInstancing ? 1 : 4;
  55756. }
  55757. if (this._vertexBuffer) {
  55758. this._vertexBuffer.update(this._vertexData);
  55759. }
  55760. }
  55761. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55762. this.stop();
  55763. }
  55764. };
  55765. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  55766. this._appendParticleVertex(offset++, particle, 0, 0);
  55767. if (!this._useInstancing) {
  55768. this._appendParticleVertex(offset++, particle, 1, 0);
  55769. this._appendParticleVertex(offset++, particle, 1, 1);
  55770. this._appendParticleVertex(offset++, particle, 0, 1);
  55771. }
  55772. };
  55773. /**
  55774. * Rebuilds the particle system.
  55775. */
  55776. ParticleSystem.prototype.rebuild = function () {
  55777. this._createIndexBuffer();
  55778. if (this._vertexBuffer) {
  55779. this._vertexBuffer._rebuild();
  55780. }
  55781. };
  55782. /**
  55783. * Is this system ready to be used/rendered
  55784. * @return true if the system is ready
  55785. */
  55786. ParticleSystem.prototype.isReady = function () {
  55787. var effect = this._getEffect();
  55788. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55789. return false;
  55790. }
  55791. return true;
  55792. };
  55793. /**
  55794. * Renders the particle system in its current state.
  55795. * @returns the current number of particles
  55796. */
  55797. ParticleSystem.prototype.render = function () {
  55798. var effect = this._getEffect();
  55799. // Check
  55800. if (!this.isReady() || !this._particles.length) {
  55801. return 0;
  55802. }
  55803. var engine = this._scene.getEngine();
  55804. // Render
  55805. engine.enableEffect(effect);
  55806. engine.setState(false);
  55807. var viewMatrix = this._scene.getViewMatrix();
  55808. effect.setTexture("diffuseSampler", this.particleTexture);
  55809. effect.setMatrix("view", viewMatrix);
  55810. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55811. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55812. var baseSize = this.particleTexture.getBaseSize();
  55813. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55814. }
  55815. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55816. if (this._scene.clipPlane) {
  55817. var clipPlane = this._scene.clipPlane;
  55818. var invView = viewMatrix.clone();
  55819. invView.invert();
  55820. effect.setMatrix("invView", invView);
  55821. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55822. }
  55823. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55824. // Draw order
  55825. switch (this.blendMode) {
  55826. case ParticleSystem.BLENDMODE_ADD:
  55827. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  55828. break;
  55829. case ParticleSystem.BLENDMODE_ONEONE:
  55830. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55831. break;
  55832. case ParticleSystem.BLENDMODE_STANDARD:
  55833. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55834. break;
  55835. }
  55836. if (this.forceDepthWrite) {
  55837. engine.setDepthWrite(true);
  55838. }
  55839. if (this._useInstancing) {
  55840. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  55841. engine.unbindInstanceAttributes();
  55842. }
  55843. else {
  55844. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55845. }
  55846. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55847. return this._particles.length;
  55848. };
  55849. /**
  55850. * Disposes the particle system and free the associated resources
  55851. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55852. */
  55853. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55854. if (disposeTexture === void 0) { disposeTexture = true; }
  55855. if (this._vertexBuffer) {
  55856. this._vertexBuffer.dispose();
  55857. this._vertexBuffer = null;
  55858. }
  55859. if (this._spriteBuffer) {
  55860. this._spriteBuffer.dispose();
  55861. this._spriteBuffer = null;
  55862. }
  55863. if (this._indexBuffer) {
  55864. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55865. this._indexBuffer = null;
  55866. }
  55867. if (disposeTexture && this.particleTexture) {
  55868. this.particleTexture.dispose();
  55869. this.particleTexture = null;
  55870. }
  55871. this._removeFromRoot();
  55872. // Remove from scene
  55873. var index = this._scene.particleSystems.indexOf(this);
  55874. if (index > -1) {
  55875. this._scene.particleSystems.splice(index, 1);
  55876. }
  55877. // Callback
  55878. this.onDisposeObservable.notifyObservers(this);
  55879. this.onDisposeObservable.clear();
  55880. };
  55881. /**
  55882. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  55883. * @param radius The radius of the sphere to emit from
  55884. * @returns the emitter
  55885. */
  55886. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  55887. if (radius === void 0) { radius = 1; }
  55888. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  55889. this.particleEmitterType = particleEmitter;
  55890. return particleEmitter;
  55891. };
  55892. /**
  55893. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  55894. * @param radius The radius of the sphere to emit from
  55895. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55896. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55897. * @returns the emitter
  55898. */
  55899. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55900. if (radius === void 0) { radius = 1; }
  55901. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55902. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55903. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55904. this.particleEmitterType = particleEmitter;
  55905. return particleEmitter;
  55906. };
  55907. /**
  55908. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  55909. * @param radius The radius of the cone to emit from
  55910. * @param angle The base angle of the cone
  55911. * @returns the emitter
  55912. */
  55913. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55914. if (radius === void 0) { radius = 1; }
  55915. if (angle === void 0) { angle = Math.PI / 4; }
  55916. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55917. this.particleEmitterType = particleEmitter;
  55918. return particleEmitter;
  55919. };
  55920. // 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.
  55921. /**
  55922. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55923. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55924. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55925. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55926. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55927. * @returns the emitter
  55928. */
  55929. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55930. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55931. this.particleEmitterType = particleEmitter;
  55932. this.direction1 = direction1;
  55933. this.direction2 = direction2;
  55934. this.minEmitBox = minEmitBox;
  55935. this.maxEmitBox = maxEmitBox;
  55936. return particleEmitter;
  55937. };
  55938. // Clone
  55939. /**
  55940. * Clones the particle system.
  55941. * @param name The name of the cloned object
  55942. * @param newEmitter The new emitter to use
  55943. * @returns the cloned particle system
  55944. */
  55945. ParticleSystem.prototype.clone = function (name, newEmitter) {
  55946. var custom = null;
  55947. var program = null;
  55948. if (this.customShader != null) {
  55949. program = this.customShader;
  55950. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55951. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55952. }
  55953. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  55954. result.customShader = program;
  55955. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  55956. if (newEmitter === undefined) {
  55957. newEmitter = this.emitter;
  55958. }
  55959. result.emitter = newEmitter;
  55960. if (this.particleTexture) {
  55961. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  55962. }
  55963. if (!this.preventAutoStart) {
  55964. result.start();
  55965. }
  55966. return result;
  55967. };
  55968. /**
  55969. * Serializes the particle system to a JSON object.
  55970. * @returns the JSON object
  55971. */
  55972. ParticleSystem.prototype.serialize = function () {
  55973. var serializationObject = {};
  55974. ParticleSystem._Serialize(serializationObject, this);
  55975. serializationObject.textureMask = this.textureMask.asArray();
  55976. serializationObject.customShader = this.customShader;
  55977. serializationObject.preventAutoStart = this.preventAutoStart;
  55978. serializationObject.startSpriteCellID = this.startSpriteCellID;
  55979. serializationObject.endSpriteCellID = this.endSpriteCellID;
  55980. serializationObject.spriteCellLoop = this.spriteCellLoop;
  55981. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  55982. serializationObject.spriteCellWidth = this.spriteCellWidth;
  55983. serializationObject.spriteCellHeight = this.spriteCellHeight;
  55984. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  55985. return serializationObject;
  55986. };
  55987. /** @hidden */
  55988. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  55989. serializationObject.name = particleSystem.name;
  55990. serializationObject.id = particleSystem.id;
  55991. serializationObject.capacity = particleSystem.getCapacity();
  55992. // Emitter
  55993. if (particleSystem.emitter.position) {
  55994. var emitterMesh = particleSystem.emitter;
  55995. serializationObject.emitterId = emitterMesh.id;
  55996. }
  55997. else {
  55998. var emitterPosition = particleSystem.emitter;
  55999. serializationObject.emitter = emitterPosition.asArray();
  56000. }
  56001. // Emitter
  56002. if (particleSystem.particleEmitterType) {
  56003. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56004. }
  56005. if (particleSystem.particleTexture) {
  56006. serializationObject.textureName = particleSystem.particleTexture.name;
  56007. }
  56008. // Animations
  56009. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56010. // Particle system
  56011. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56012. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56013. serializationObject.minSize = particleSystem.minSize;
  56014. serializationObject.maxSize = particleSystem.maxSize;
  56015. serializationObject.minScaleX = particleSystem.minScaleX;
  56016. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56017. serializationObject.minScaleY = particleSystem.minScaleY;
  56018. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56019. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56020. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56021. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56022. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56023. serializationObject.emitRate = particleSystem.emitRate;
  56024. serializationObject.gravity = particleSystem.gravity.asArray();
  56025. serializationObject.color1 = particleSystem.color1.asArray();
  56026. serializationObject.color2 = particleSystem.color2.asArray();
  56027. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56028. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56029. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56030. serializationObject.blendMode = particleSystem.blendMode;
  56031. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56032. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56033. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56034. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56035. var colorGradients = particleSystem.getColorGradients();
  56036. if (colorGradients) {
  56037. serializationObject.colorGradients = [];
  56038. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56039. var colorGradient = colorGradients_1[_i];
  56040. serializationObject.colorGradients.push({
  56041. gradient: colorGradient.gradient,
  56042. color: colorGradient.color.asArray()
  56043. });
  56044. }
  56045. }
  56046. var sizeGradients = particleSystem.getSizeGradients();
  56047. if (sizeGradients) {
  56048. serializationObject.sizeGradients = [];
  56049. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56050. var sizeGradient = sizeGradients_1[_a];
  56051. serializationObject.sizeGradients.push({
  56052. gradient: sizeGradient.gradient,
  56053. factor: sizeGradient.factor
  56054. });
  56055. }
  56056. }
  56057. };
  56058. /** @hidden */
  56059. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56060. // Texture
  56061. if (parsedParticleSystem.textureName) {
  56062. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56063. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56064. }
  56065. // Emitter
  56066. if (parsedParticleSystem.emitterId) {
  56067. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56068. }
  56069. else {
  56070. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56071. }
  56072. // Animations
  56073. if (parsedParticleSystem.animations) {
  56074. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56075. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56076. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56077. }
  56078. }
  56079. if (parsedParticleSystem.autoAnimate) {
  56080. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56081. }
  56082. // Particle system
  56083. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56084. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56085. particleSystem.minSize = parsedParticleSystem.minSize;
  56086. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56087. if (parsedParticleSystem.minScaleX) {
  56088. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56089. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56090. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56091. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56092. }
  56093. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56094. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56095. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56096. }
  56097. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56098. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56099. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56100. }
  56101. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56102. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56103. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56104. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56105. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56106. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56107. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56108. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56109. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56110. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56111. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56112. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56113. if (parsedParticleSystem.colorGradients) {
  56114. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56115. var colorGradient = _a[_i];
  56116. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color));
  56117. }
  56118. }
  56119. if (parsedParticleSystem.sizeGradients) {
  56120. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56121. var sizeGradient = _c[_b];
  56122. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor);
  56123. }
  56124. }
  56125. // Emitter
  56126. if (parsedParticleSystem.particleEmitterType) {
  56127. var emitterType = void 0;
  56128. switch (parsedParticleSystem.particleEmitterType.type) {
  56129. case "SphereEmitter":
  56130. emitterType = new BABYLON.SphereParticleEmitter();
  56131. break;
  56132. case "SphereDirectedParticleEmitter":
  56133. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56134. break;
  56135. case "ConeEmitter":
  56136. emitterType = new BABYLON.ConeParticleEmitter();
  56137. break;
  56138. case "BoxEmitter":
  56139. default:
  56140. emitterType = new BABYLON.BoxParticleEmitter();
  56141. break;
  56142. }
  56143. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56144. particleSystem.particleEmitterType = emitterType;
  56145. }
  56146. };
  56147. /**
  56148. * Parses a JSON object to create a particle system.
  56149. * @param parsedParticleSystem The JSON object to parse
  56150. * @param scene The scene to create the particle system in
  56151. * @param rootUrl The root url to use to load external dependencies like texture
  56152. * @returns the Parsed particle system
  56153. */
  56154. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56155. var name = parsedParticleSystem.name;
  56156. var custom = null;
  56157. var program = null;
  56158. if (parsedParticleSystem.customShader) {
  56159. program = parsedParticleSystem.customShader;
  56160. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56161. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56162. }
  56163. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56164. particleSystem.customShader = program;
  56165. if (parsedParticleSystem.id) {
  56166. particleSystem.id = parsedParticleSystem.id;
  56167. }
  56168. // Auto start
  56169. if (parsedParticleSystem.preventAutoStart) {
  56170. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56171. }
  56172. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56173. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56174. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56175. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56176. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56177. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56178. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56179. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56180. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56181. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56182. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56183. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56184. if (!particleSystem.preventAutoStart) {
  56185. particleSystem.start();
  56186. }
  56187. return particleSystem;
  56188. };
  56189. /**
  56190. * Source color is added to the destination color without alpha affecting the result.
  56191. */
  56192. ParticleSystem.BLENDMODE_ONEONE = 0;
  56193. /**
  56194. * Blend current color and particle color using particle’s alpha.
  56195. */
  56196. ParticleSystem.BLENDMODE_STANDARD = 1;
  56197. /**
  56198. * Add current color and particle color multiplied by particle’s alpha.
  56199. */
  56200. ParticleSystem.BLENDMODE_ADD = 2;
  56201. return ParticleSystem;
  56202. }());
  56203. BABYLON.ParticleSystem = ParticleSystem;
  56204. })(BABYLON || (BABYLON = {}));
  56205. //# sourceMappingURL=babylon.particleSystem.js.map
  56206. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56207. var BABYLON;
  56208. (function (BABYLON) {
  56209. /**
  56210. * Particle emitter emitting particles from the inside of a box.
  56211. * It emits the particles randomly between 2 given directions.
  56212. */
  56213. var BoxParticleEmitter = /** @class */ (function () {
  56214. /**
  56215. * Creates a new instance BoxParticleEmitter
  56216. */
  56217. function BoxParticleEmitter() {
  56218. /**
  56219. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56220. */
  56221. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56222. /**
  56223. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56224. */
  56225. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56226. /**
  56227. * 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.
  56228. */
  56229. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56230. /**
  56231. * 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.
  56232. */
  56233. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56234. }
  56235. /**
  56236. * Called by the particle System when the direction is computed for the created particle.
  56237. * @param worldMatrix is the world matrix of the particle system
  56238. * @param directionToUpdate is the direction vector to update with the result
  56239. * @param particle is the particle we are computed the direction for
  56240. */
  56241. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56242. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56243. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56244. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56245. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56246. };
  56247. /**
  56248. * Called by the particle System when the position is computed for the created particle.
  56249. * @param worldMatrix is the world matrix of the particle system
  56250. * @param positionToUpdate is the position vector to update with the result
  56251. * @param particle is the particle we are computed the position for
  56252. */
  56253. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56254. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56255. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56256. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56257. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56258. };
  56259. /**
  56260. * Clones the current emitter and returns a copy of it
  56261. * @returns the new emitter
  56262. */
  56263. BoxParticleEmitter.prototype.clone = function () {
  56264. var newOne = new BoxParticleEmitter();
  56265. BABYLON.Tools.DeepCopy(this, newOne);
  56266. return newOne;
  56267. };
  56268. /**
  56269. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56270. * @param effect defines the update shader
  56271. */
  56272. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56273. effect.setVector3("direction1", this.direction1);
  56274. effect.setVector3("direction2", this.direction2);
  56275. effect.setVector3("minEmitBox", this.minEmitBox);
  56276. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56277. };
  56278. /**
  56279. * Returns a string to use to update the GPU particles update shader
  56280. * @returns a string containng the defines string
  56281. */
  56282. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56283. return "#define BOXEMITTER";
  56284. };
  56285. /**
  56286. * Returns the string "BoxEmitter"
  56287. * @returns a string containing the class name
  56288. */
  56289. BoxParticleEmitter.prototype.getClassName = function () {
  56290. return "BoxEmitter";
  56291. };
  56292. /**
  56293. * Serializes the particle system to a JSON object.
  56294. * @returns the JSON object
  56295. */
  56296. BoxParticleEmitter.prototype.serialize = function () {
  56297. var serializationObject = {};
  56298. serializationObject.type = this.getClassName();
  56299. serializationObject.direction1 = this.direction1.asArray();
  56300. serializationObject.direction2 = this.direction2.asArray();
  56301. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56302. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56303. return serializationObject;
  56304. };
  56305. /**
  56306. * Parse properties from a JSON object
  56307. * @param serializationObject defines the JSON object
  56308. */
  56309. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56310. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56311. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56312. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56313. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56314. };
  56315. return BoxParticleEmitter;
  56316. }());
  56317. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56318. })(BABYLON || (BABYLON = {}));
  56319. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56320. var BABYLON;
  56321. (function (BABYLON) {
  56322. /**
  56323. * Particle emitter emitting particles from the inside of a cone.
  56324. * It emits the particles alongside the cone volume from the base to the particle.
  56325. * The emission direction might be randomized.
  56326. */
  56327. var ConeParticleEmitter = /** @class */ (function () {
  56328. /**
  56329. * Creates a new instance ConeParticleEmitter
  56330. * @param radius the radius of the emission cone (1 by default)
  56331. * @param angles the cone base angle (PI by default)
  56332. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56333. */
  56334. function ConeParticleEmitter(radius, angle,
  56335. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56336. directionRandomizer) {
  56337. if (radius === void 0) { radius = 1; }
  56338. if (angle === void 0) { angle = Math.PI; }
  56339. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56340. this.directionRandomizer = directionRandomizer;
  56341. this.angle = angle;
  56342. this.radius = radius;
  56343. }
  56344. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56345. /**
  56346. * Gets or sets the radius of the emission cone
  56347. */
  56348. get: function () {
  56349. return this._radius;
  56350. },
  56351. set: function (value) {
  56352. this._radius = value;
  56353. this._buildHeight();
  56354. },
  56355. enumerable: true,
  56356. configurable: true
  56357. });
  56358. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56359. /**
  56360. * Gets or sets the angle of the emission cone
  56361. */
  56362. get: function () {
  56363. return this._angle;
  56364. },
  56365. set: function (value) {
  56366. this._angle = value;
  56367. this._buildHeight();
  56368. },
  56369. enumerable: true,
  56370. configurable: true
  56371. });
  56372. ConeParticleEmitter.prototype._buildHeight = function () {
  56373. if (this._angle !== 0) {
  56374. this._height = this._radius / Math.tan(this._angle / 2);
  56375. }
  56376. else {
  56377. this._height = 1;
  56378. }
  56379. };
  56380. /**
  56381. * Called by the particle System when the direction is computed for the created particle.
  56382. * @param worldMatrix is the world matrix of the particle system
  56383. * @param directionToUpdate is the direction vector to update with the result
  56384. * @param particle is the particle we are computed the direction for
  56385. */
  56386. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56387. if (this._angle === 0) {
  56388. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56389. }
  56390. else {
  56391. // measure the direction Vector from the emitter to the particle.
  56392. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56393. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56394. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56395. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56396. direction.x += randX;
  56397. direction.y += randY;
  56398. direction.z += randZ;
  56399. direction.normalize();
  56400. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56401. }
  56402. };
  56403. /**
  56404. * Called by the particle System when the position is computed for the created particle.
  56405. * @param worldMatrix is the world matrix of the particle system
  56406. * @param positionToUpdate is the position vector to update with the result
  56407. * @param particle is the particle we are computed the position for
  56408. */
  56409. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56410. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56411. var h = BABYLON.Scalar.RandomRange(0, 1);
  56412. // Better distribution in a cone at normal angles.
  56413. h = 1 - h * h;
  56414. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56415. radius = radius * h;
  56416. var randX = radius * Math.sin(s);
  56417. var randZ = radius * Math.cos(s);
  56418. var randY = h * this._height;
  56419. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56420. };
  56421. /**
  56422. * Clones the current emitter and returns a copy of it
  56423. * @returns the new emitter
  56424. */
  56425. ConeParticleEmitter.prototype.clone = function () {
  56426. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56427. BABYLON.Tools.DeepCopy(this, newOne);
  56428. return newOne;
  56429. };
  56430. /**
  56431. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56432. * @param effect defines the update shader
  56433. */
  56434. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56435. effect.setFloat("radius", this._radius);
  56436. effect.setFloat("coneAngle", this._angle);
  56437. effect.setFloat("height", this._height);
  56438. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56439. };
  56440. /**
  56441. * Returns a string to use to update the GPU particles update shader
  56442. * @returns a string containng the defines string
  56443. */
  56444. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56445. return "#define CONEEMITTER";
  56446. };
  56447. /**
  56448. * Returns the string "BoxEmitter"
  56449. * @returns a string containing the class name
  56450. */
  56451. ConeParticleEmitter.prototype.getClassName = function () {
  56452. return "ConeEmitter";
  56453. };
  56454. /**
  56455. * Serializes the particle system to a JSON object.
  56456. * @returns the JSON object
  56457. */
  56458. ConeParticleEmitter.prototype.serialize = function () {
  56459. var serializationObject = {};
  56460. serializationObject.type = this.getClassName();
  56461. serializationObject.radius = this._radius;
  56462. serializationObject.angle = this._angle;
  56463. serializationObject.directionRandomizer = this.directionRandomizer;
  56464. return serializationObject;
  56465. };
  56466. /**
  56467. * Parse properties from a JSON object
  56468. * @param serializationObject defines the JSON object
  56469. */
  56470. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56471. this.radius = serializationObject.radius;
  56472. this.angle = serializationObject.angle;
  56473. this.directionRandomizer = serializationObject.directionRandomizer;
  56474. };
  56475. return ConeParticleEmitter;
  56476. }());
  56477. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56478. })(BABYLON || (BABYLON = {}));
  56479. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56480. var BABYLON;
  56481. (function (BABYLON) {
  56482. /**
  56483. * Particle emitter emitting particles from the inside of a sphere.
  56484. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56485. */
  56486. var SphereParticleEmitter = /** @class */ (function () {
  56487. /**
  56488. * Creates a new instance SphereParticleEmitter
  56489. * @param radius the radius of the emission sphere (1 by default)
  56490. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56491. */
  56492. function SphereParticleEmitter(
  56493. /**
  56494. * The radius of the emission sphere.
  56495. */
  56496. radius,
  56497. /**
  56498. * How much to randomize the particle direction [0-1].
  56499. */
  56500. directionRandomizer) {
  56501. if (radius === void 0) { radius = 1; }
  56502. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56503. this.radius = radius;
  56504. this.directionRandomizer = directionRandomizer;
  56505. /**
  56506. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56507. */
  56508. this.radiusRange = 1;
  56509. }
  56510. /**
  56511. * Called by the particle System when the direction is computed for the created particle.
  56512. * @param worldMatrix is the world matrix of the particle system
  56513. * @param directionToUpdate is the direction vector to update with the result
  56514. * @param particle is the particle we are computed the direction for
  56515. */
  56516. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56517. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56518. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56519. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56520. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56521. direction.x += randX;
  56522. direction.y += randY;
  56523. direction.z += randZ;
  56524. direction.normalize();
  56525. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56526. };
  56527. /**
  56528. * Called by the particle System when the position is computed for the created particle.
  56529. * @param worldMatrix is the world matrix of the particle system
  56530. * @param positionToUpdate is the position vector to update with the result
  56531. * @param particle is the particle we are computed the position for
  56532. */
  56533. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56534. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56535. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56536. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56537. var theta = Math.acos(2 * v - 1);
  56538. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56539. var randY = randRadius * Math.cos(theta);
  56540. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56541. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56542. };
  56543. /**
  56544. * Clones the current emitter and returns a copy of it
  56545. * @returns the new emitter
  56546. */
  56547. SphereParticleEmitter.prototype.clone = function () {
  56548. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56549. BABYLON.Tools.DeepCopy(this, newOne);
  56550. return newOne;
  56551. };
  56552. /**
  56553. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56554. * @param effect defines the update shader
  56555. */
  56556. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56557. effect.setFloat("radius", this.radius);
  56558. effect.setFloat("radiusRange", this.radiusRange);
  56559. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56560. };
  56561. /**
  56562. * Returns a string to use to update the GPU particles update shader
  56563. * @returns a string containng the defines string
  56564. */
  56565. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56566. return "#define SPHEREEMITTER";
  56567. };
  56568. /**
  56569. * Returns the string "SphereParticleEmitter"
  56570. * @returns a string containing the class name
  56571. */
  56572. SphereParticleEmitter.prototype.getClassName = function () {
  56573. return "SphereParticleEmitter";
  56574. };
  56575. /**
  56576. * Serializes the particle system to a JSON object.
  56577. * @returns the JSON object
  56578. */
  56579. SphereParticleEmitter.prototype.serialize = function () {
  56580. var serializationObject = {};
  56581. serializationObject.type = this.getClassName();
  56582. serializationObject.radius = this.radius;
  56583. serializationObject.directionRandomizer = this.directionRandomizer;
  56584. return serializationObject;
  56585. };
  56586. /**
  56587. * Parse properties from a JSON object
  56588. * @param serializationObject defines the JSON object
  56589. */
  56590. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56591. this.radius = serializationObject.radius;
  56592. this.directionRandomizer = serializationObject.directionRandomizer;
  56593. };
  56594. return SphereParticleEmitter;
  56595. }());
  56596. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56597. /**
  56598. * Particle emitter emitting particles from the inside of a sphere.
  56599. * It emits the particles randomly between two vectors.
  56600. */
  56601. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56602. __extends(SphereDirectedParticleEmitter, _super);
  56603. /**
  56604. * Creates a new instance SphereDirectedParticleEmitter
  56605. * @param radius the radius of the emission sphere (1 by default)
  56606. * @param direction1 the min limit of the emission direction (up vector by default)
  56607. * @param direction2 the max limit of the emission direction (up vector by default)
  56608. */
  56609. function SphereDirectedParticleEmitter(radius,
  56610. /**
  56611. * The min limit of the emission direction.
  56612. */
  56613. direction1,
  56614. /**
  56615. * The max limit of the emission direction.
  56616. */
  56617. direction2) {
  56618. if (radius === void 0) { radius = 1; }
  56619. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56620. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56621. var _this = _super.call(this, radius) || this;
  56622. _this.direction1 = direction1;
  56623. _this.direction2 = direction2;
  56624. return _this;
  56625. }
  56626. /**
  56627. * Called by the particle System when the direction is computed for the created particle.
  56628. * @param worldMatrix is the world matrix of the particle system
  56629. * @param directionToUpdate is the direction vector to update with the result
  56630. * @param particle is the particle we are computed the direction for
  56631. */
  56632. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56633. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56634. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56635. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56636. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56637. };
  56638. /**
  56639. * Clones the current emitter and returns a copy of it
  56640. * @returns the new emitter
  56641. */
  56642. SphereDirectedParticleEmitter.prototype.clone = function () {
  56643. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56644. BABYLON.Tools.DeepCopy(this, newOne);
  56645. return newOne;
  56646. };
  56647. /**
  56648. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56649. * @param effect defines the update shader
  56650. */
  56651. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56652. effect.setFloat("radius", this.radius);
  56653. effect.setFloat("radiusRange", this.radiusRange);
  56654. effect.setVector3("direction1", this.direction1);
  56655. effect.setVector3("direction2", this.direction2);
  56656. };
  56657. /**
  56658. * Returns a string to use to update the GPU particles update shader
  56659. * @returns a string containng the defines string
  56660. */
  56661. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56662. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56663. };
  56664. /**
  56665. * Returns the string "SphereDirectedParticleEmitter"
  56666. * @returns a string containing the class name
  56667. */
  56668. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56669. return "SphereDirectedParticleEmitter";
  56670. };
  56671. /**
  56672. * Serializes the particle system to a JSON object.
  56673. * @returns the JSON object
  56674. */
  56675. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56676. var serializationObject = _super.prototype.serialize.call(this);
  56677. serializationObject.direction1 = this.direction1.asArray();
  56678. serializationObject.direction2 = this.direction2.asArray();
  56679. return serializationObject;
  56680. };
  56681. /**
  56682. * Parse properties from a JSON object
  56683. * @param serializationObject defines the JSON object
  56684. */
  56685. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56686. _super.prototype.parse.call(this, serializationObject);
  56687. this.direction1.copyFrom(serializationObject.direction1);
  56688. this.direction2.copyFrom(serializationObject.direction2);
  56689. };
  56690. return SphereDirectedParticleEmitter;
  56691. }(SphereParticleEmitter));
  56692. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56693. })(BABYLON || (BABYLON = {}));
  56694. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56695. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56696. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56697. s = arguments[i];
  56698. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56699. t[p] = s[p];
  56700. }
  56701. return t;
  56702. };
  56703. var BABYLON;
  56704. (function (BABYLON) {
  56705. /**
  56706. * This represents a GPU particle system in Babylon
  56707. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56708. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56709. */
  56710. var GPUParticleSystem = /** @class */ (function () {
  56711. /**
  56712. * Instantiates a GPU particle system.
  56713. * 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.
  56714. * @param name The name of the particle system
  56715. * @param capacity The max number of particles alive at the same time
  56716. * @param scene The scene the particle system belongs to
  56717. */
  56718. function GPUParticleSystem(name, options, scene) {
  56719. /**
  56720. * The emitter represents the Mesh or position we are attaching the particle system to.
  56721. */
  56722. this.emitter = null;
  56723. /**
  56724. * The rendering group used by the Particle system to chose when to render.
  56725. */
  56726. this.renderingGroupId = 0;
  56727. /**
  56728. * The layer mask we are rendering the particles through.
  56729. */
  56730. this.layerMask = 0x0FFFFFFF;
  56731. this._accumulatedCount = 0;
  56732. this._targetIndex = 0;
  56733. this._currentRenderId = -1;
  56734. this._started = false;
  56735. this._stopped = false;
  56736. this._timeDelta = 0;
  56737. this._attributesStrideSize = 21;
  56738. this._actualFrame = 0;
  56739. /**
  56740. * List of animations used by the particle system.
  56741. */
  56742. this.animations = [];
  56743. /**
  56744. * An event triggered when the system is disposed.
  56745. */
  56746. this.onDisposeObservable = new BABYLON.Observable();
  56747. /**
  56748. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56749. */
  56750. this.updateSpeed = 0.01;
  56751. /**
  56752. * The amount of time the particle system is running (depends of the overall update speed).
  56753. */
  56754. this.targetStopDuration = 0;
  56755. /**
  56756. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56757. */
  56758. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56759. /**
  56760. * Minimum life time of emitting particles.
  56761. */
  56762. this.minLifeTime = 1;
  56763. /**
  56764. * Maximum life time of emitting particles.
  56765. */
  56766. this.maxLifeTime = 1;
  56767. /**
  56768. * Minimum Size of emitting particles.
  56769. */
  56770. this.minSize = 1;
  56771. /**
  56772. * Maximum Size of emitting particles.
  56773. */
  56774. this.maxSize = 1;
  56775. /**
  56776. * Minimum scale of emitting particles on X axis.
  56777. */
  56778. this.minScaleX = 1;
  56779. /**
  56780. * Maximum scale of emitting particles on X axis.
  56781. */
  56782. this.maxScaleX = 1;
  56783. /**
  56784. * Minimum scale of emitting particles on Y axis.
  56785. */
  56786. this.minScaleY = 1;
  56787. /**
  56788. * Maximum scale of emitting particles on Y axis.
  56789. */
  56790. this.maxScaleY = 1;
  56791. /**
  56792. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56793. */
  56794. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56795. /**
  56796. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56797. */
  56798. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56799. /**
  56800. * Color the particle will have at the end of its lifetime.
  56801. */
  56802. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  56803. /**
  56804. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  56805. */
  56806. this.emitRate = 100;
  56807. /**
  56808. * You can use gravity if you want to give an orientation to your particles.
  56809. */
  56810. this.gravity = BABYLON.Vector3.Zero();
  56811. /**
  56812. * Minimum power of emitting particles.
  56813. */
  56814. this.minEmitPower = 1;
  56815. /**
  56816. * Maximum power of emitting particles.
  56817. */
  56818. this.maxEmitPower = 1;
  56819. /**
  56820. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56821. */
  56822. this.minAngularSpeed = 0;
  56823. /**
  56824. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56825. */
  56826. this.maxAngularSpeed = 0;
  56827. /**
  56828. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56829. * to override the particles.
  56830. */
  56831. this.forceDepthWrite = false;
  56832. this._preWarmDone = false;
  56833. /** 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 */
  56834. this.preWarmCycles = 0;
  56835. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  56836. this.preWarmStepOffset = 1;
  56837. /**
  56838. * Gets or sets the minimal initial rotation in radians.
  56839. */
  56840. this.minInitialRotation = 0;
  56841. /**
  56842. * Gets or sets the maximal initial rotation in radians.
  56843. */
  56844. this.maxInitialRotation = 0;
  56845. this._isBillboardBased = true;
  56846. this._colorGradients = null;
  56847. this._sizeGradients = null;
  56848. this.id = name;
  56849. this.name = name;
  56850. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56851. this._engine = this._scene.getEngine();
  56852. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  56853. var optionsAsNumber = options;
  56854. if (isFinite(optionsAsNumber)) {
  56855. fullOptions.capacity = optionsAsNumber;
  56856. }
  56857. this._capacity = fullOptions.capacity;
  56858. this._activeCount = fullOptions.capacity;
  56859. this._currentActiveCount = 0;
  56860. this._scene.particleSystems.push(this);
  56861. this._updateEffectOptions = {
  56862. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "initialSize"],
  56863. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  56864. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  56865. "angleRange", "radiusRange"],
  56866. uniformBuffersNames: [],
  56867. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler"],
  56868. defines: "",
  56869. fallbacks: null,
  56870. onCompiled: null,
  56871. onError: null,
  56872. indexParameters: null,
  56873. maxSimultaneousLights: 0,
  56874. transformFeedbackVaryings: []
  56875. };
  56876. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56877. // Random data
  56878. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  56879. var d = [];
  56880. for (var i = 0; i < maxTextureSize; ++i) {
  56881. d.push(Math.random());
  56882. d.push(Math.random());
  56883. d.push(Math.random());
  56884. d.push(Math.random());
  56885. }
  56886. 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);
  56887. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56888. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56889. d = [];
  56890. for (var i = 0; i < maxTextureSize; ++i) {
  56891. d.push(Math.random());
  56892. d.push(Math.random());
  56893. d.push(Math.random());
  56894. d.push(Math.random());
  56895. }
  56896. 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);
  56897. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56898. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56899. this._randomTextureSize = maxTextureSize;
  56900. }
  56901. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  56902. /**
  56903. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  56904. */
  56905. get: function () {
  56906. if (!BABYLON.Engine.LastCreatedEngine) {
  56907. return false;
  56908. }
  56909. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  56910. },
  56911. enumerable: true,
  56912. configurable: true
  56913. });
  56914. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  56915. /**
  56916. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56917. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56918. */
  56919. get: function () {
  56920. if (this.particleEmitterType.direction1) {
  56921. return this.particleEmitterType.direction1;
  56922. }
  56923. return BABYLON.Vector3.Zero();
  56924. },
  56925. set: function (value) {
  56926. if (this.particleEmitterType.direction1) {
  56927. this.particleEmitterType.direction1 = value;
  56928. }
  56929. },
  56930. enumerable: true,
  56931. configurable: true
  56932. });
  56933. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  56934. /**
  56935. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56936. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56937. */
  56938. get: function () {
  56939. if (this.particleEmitterType.direction2) {
  56940. return this.particleEmitterType.direction2;
  56941. }
  56942. return BABYLON.Vector3.Zero();
  56943. },
  56944. set: function (value) {
  56945. if (this.particleEmitterType.direction2) {
  56946. this.particleEmitterType.direction2 = value;
  56947. }
  56948. },
  56949. enumerable: true,
  56950. configurable: true
  56951. });
  56952. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  56953. /**
  56954. * 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.
  56955. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56956. */
  56957. get: function () {
  56958. if (this.particleEmitterType.minEmitBox) {
  56959. return this.particleEmitterType.minEmitBox;
  56960. }
  56961. return BABYLON.Vector3.Zero();
  56962. },
  56963. set: function (value) {
  56964. if (this.particleEmitterType.minEmitBox) {
  56965. this.particleEmitterType.minEmitBox = value;
  56966. }
  56967. },
  56968. enumerable: true,
  56969. configurable: true
  56970. });
  56971. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  56972. /**
  56973. * 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.
  56974. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56975. */
  56976. get: function () {
  56977. if (this.particleEmitterType.maxEmitBox) {
  56978. return this.particleEmitterType.maxEmitBox;
  56979. }
  56980. return BABYLON.Vector3.Zero();
  56981. },
  56982. set: function (value) {
  56983. if (this.particleEmitterType.maxEmitBox) {
  56984. this.particleEmitterType.maxEmitBox = value;
  56985. }
  56986. },
  56987. enumerable: true,
  56988. configurable: true
  56989. });
  56990. /**
  56991. * Gets the maximum number of particles active at the same time.
  56992. * @returns The max number of active particles.
  56993. */
  56994. GPUParticleSystem.prototype.getCapacity = function () {
  56995. return this._capacity;
  56996. };
  56997. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  56998. /**
  56999. * Gets or set the number of active particles
  57000. */
  57001. get: function () {
  57002. return this._activeCount;
  57003. },
  57004. set: function (value) {
  57005. this._activeCount = Math.min(value, this._capacity);
  57006. },
  57007. enumerable: true,
  57008. configurable: true
  57009. });
  57010. /**
  57011. * Is this system ready to be used/rendered
  57012. * @return true if the system is ready
  57013. */
  57014. GPUParticleSystem.prototype.isReady = function () {
  57015. if (!this._updateEffect) {
  57016. this._recreateUpdateEffect();
  57017. this._recreateRenderEffect();
  57018. return false;
  57019. }
  57020. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57021. return false;
  57022. }
  57023. return true;
  57024. };
  57025. /**
  57026. * Gets Wether the system has been started.
  57027. * @returns True if it has been started, otherwise false.
  57028. */
  57029. GPUParticleSystem.prototype.isStarted = function () {
  57030. return this._started;
  57031. };
  57032. /**
  57033. * Starts the particle system and begins to emit.
  57034. */
  57035. GPUParticleSystem.prototype.start = function () {
  57036. this._started = true;
  57037. this._stopped = false;
  57038. this._preWarmDone = false;
  57039. };
  57040. /**
  57041. * Stops the particle system.
  57042. */
  57043. GPUParticleSystem.prototype.stop = function () {
  57044. this._stopped = true;
  57045. };
  57046. /**
  57047. * Remove all active particles
  57048. */
  57049. GPUParticleSystem.prototype.reset = function () {
  57050. this._releaseBuffers();
  57051. this._releaseVAOs();
  57052. this._currentActiveCount = 0;
  57053. this._targetIndex = 0;
  57054. };
  57055. /**
  57056. * Returns the string "GPUParticleSystem"
  57057. * @returns a string containing the class name
  57058. */
  57059. GPUParticleSystem.prototype.getClassName = function () {
  57060. return "GPUParticleSystem";
  57061. };
  57062. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  57063. /**
  57064. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57065. */
  57066. get: function () {
  57067. return this._isBillboardBased;
  57068. },
  57069. set: function (value) {
  57070. if (this._isBillboardBased === value) {
  57071. return;
  57072. }
  57073. this._isBillboardBased = value;
  57074. this._releaseBuffers();
  57075. },
  57076. enumerable: true,
  57077. configurable: true
  57078. });
  57079. /**
  57080. * Gets the current list of color gradients.
  57081. * You must use addColorGradient and removeColorGradient to udpate this list
  57082. * @returns the list of color gradients
  57083. */
  57084. GPUParticleSystem.prototype.getColorGradients = function () {
  57085. return this._colorGradients;
  57086. };
  57087. /**
  57088. * Gets the current list of size gradients.
  57089. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57090. * @returns the list of size gradients
  57091. */
  57092. GPUParticleSystem.prototype.getSizeGradients = function () {
  57093. return this._sizeGradients;
  57094. };
  57095. /**
  57096. * Adds a new color gradient
  57097. * @param gradient defines the gradient to use (between 0 and 1)
  57098. * @param color defines the color to affect to the specified gradient
  57099. */
  57100. GPUParticleSystem.prototype.addColorGradient = function (gradient, color) {
  57101. if (!this._colorGradients) {
  57102. this._colorGradients = [];
  57103. }
  57104. var colorGradient = new BABYLON.ColorGradient();
  57105. colorGradient.gradient = gradient;
  57106. colorGradient.color = color;
  57107. this._colorGradients.push(colorGradient);
  57108. this._colorGradients.sort(function (a, b) {
  57109. if (a.gradient < b.gradient) {
  57110. return -1;
  57111. }
  57112. else if (a.gradient > b.gradient) {
  57113. return 1;
  57114. }
  57115. return 0;
  57116. });
  57117. if (this._colorGradientsTexture) {
  57118. this._colorGradientsTexture.dispose();
  57119. this._colorGradientsTexture = null;
  57120. }
  57121. this._releaseBuffers();
  57122. return this;
  57123. };
  57124. /**
  57125. * Remove a specific color gradient
  57126. * @param gradient defines the gradient to remove
  57127. */
  57128. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  57129. if (!this._colorGradients) {
  57130. return this;
  57131. }
  57132. var index = 0;
  57133. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  57134. var colorGradient = _a[_i];
  57135. if (colorGradient.gradient === gradient) {
  57136. this._colorGradients.splice(index, 1);
  57137. break;
  57138. }
  57139. index++;
  57140. }
  57141. if (this._colorGradientsTexture) {
  57142. this._colorGradientsTexture.dispose();
  57143. this._colorGradientsTexture = null;
  57144. }
  57145. this._releaseBuffers();
  57146. return this;
  57147. };
  57148. /**
  57149. * Adds a new size gradient
  57150. * @param gradient defines the gradient to use (between 0 and 1)
  57151. * @param factor defines the size factor to affect to the specified gradient
  57152. */
  57153. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  57154. if (!this._sizeGradients) {
  57155. this._sizeGradients = [];
  57156. }
  57157. var sizeGradient = new BABYLON.FactorGradient();
  57158. sizeGradient.gradient = gradient;
  57159. sizeGradient.factor = factor;
  57160. this._sizeGradients.push(sizeGradient);
  57161. this._sizeGradients.sort(function (a, b) {
  57162. if (a.gradient < b.gradient) {
  57163. return -1;
  57164. }
  57165. else if (a.gradient > b.gradient) {
  57166. return 1;
  57167. }
  57168. return 0;
  57169. });
  57170. if (this._sizeGradientsTexture) {
  57171. this._sizeGradientsTexture.dispose();
  57172. this._sizeGradientsTexture = null;
  57173. }
  57174. this._releaseBuffers();
  57175. return this;
  57176. };
  57177. /**
  57178. * Remove a specific size gradient
  57179. * @param gradient defines the gradient to remove
  57180. */
  57181. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57182. if (!this._sizeGradients) {
  57183. return this;
  57184. }
  57185. var index = 0;
  57186. for (var _i = 0, _a = this._sizeGradients; _i < _a.length; _i++) {
  57187. var sizeGradient = _a[_i];
  57188. if (sizeGradient.gradient === gradient) {
  57189. this._sizeGradients.splice(index, 1);
  57190. break;
  57191. }
  57192. index++;
  57193. }
  57194. if (this._sizeGradientsTexture) {
  57195. this._sizeGradientsTexture.dispose();
  57196. this._sizeGradientsTexture = null;
  57197. }
  57198. this._releaseBuffers();
  57199. return this;
  57200. };
  57201. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57202. var updateVertexBuffers = {};
  57203. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57204. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57205. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57206. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  57207. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  57208. var offset = 12;
  57209. if (this._sizeGradientsTexture) {
  57210. updateVertexBuffers["initialSize"] = source.createVertexBuffer("initialSize", offset, 3);
  57211. offset += 3;
  57212. }
  57213. if (!this._colorGradientsTexture) {
  57214. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  57215. offset += 4;
  57216. }
  57217. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  57218. offset += 3;
  57219. if (!this._isBillboardBased) {
  57220. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  57221. offset += 3;
  57222. }
  57223. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  57224. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57225. this._engine.bindArrayBuffer(null);
  57226. return vao;
  57227. };
  57228. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57229. var renderVertexBuffers = {};
  57230. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57231. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57232. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57233. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  57234. var offset = 12;
  57235. if (this._sizeGradientsTexture) {
  57236. offset += 3;
  57237. }
  57238. if (!this._colorGradientsTexture) {
  57239. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  57240. offset += 4;
  57241. }
  57242. offset += 3; // Direction
  57243. if (!this._isBillboardBased) {
  57244. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  57245. offset += 3;
  57246. }
  57247. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2, this._attributesStrideSize, true);
  57248. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57249. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57250. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57251. this._engine.bindArrayBuffer(null);
  57252. return vao;
  57253. };
  57254. GPUParticleSystem.prototype._initialize = function (force) {
  57255. if (force === void 0) { force = false; }
  57256. if (this._buffer0 && !force) {
  57257. return;
  57258. }
  57259. var engine = this._scene.getEngine();
  57260. var data = new Array();
  57261. if (!this.isBillboardBased) {
  57262. this._attributesStrideSize += 3;
  57263. }
  57264. if (this._colorGradientsTexture) {
  57265. this._attributesStrideSize -= 4;
  57266. }
  57267. if (this._sizeGradientsTexture) {
  57268. this._attributesStrideSize += 3;
  57269. }
  57270. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57271. // position
  57272. data.push(0.0);
  57273. data.push(0.0);
  57274. data.push(0.0);
  57275. // Age and life
  57276. data.push(0.0); // create the particle as a dead one to create a new one at start
  57277. data.push(0.0);
  57278. // Seed
  57279. data.push(Math.random());
  57280. data.push(Math.random());
  57281. data.push(Math.random());
  57282. data.push(Math.random());
  57283. // Size
  57284. data.push(0.0);
  57285. data.push(0.0);
  57286. data.push(0.0);
  57287. if (this._sizeGradientsTexture) {
  57288. data.push(0.0);
  57289. data.push(0.0);
  57290. data.push(0.0);
  57291. }
  57292. if (!this._colorGradientsTexture) {
  57293. // color
  57294. data.push(0.0);
  57295. data.push(0.0);
  57296. data.push(0.0);
  57297. data.push(0.0);
  57298. }
  57299. // direction
  57300. data.push(0.0);
  57301. data.push(0.0);
  57302. data.push(0.0);
  57303. if (!this.isBillboardBased) {
  57304. // initialDirection
  57305. data.push(0.0);
  57306. data.push(0.0);
  57307. data.push(0.0);
  57308. }
  57309. // angle
  57310. data.push(0.0);
  57311. data.push(0.0);
  57312. }
  57313. // Sprite data
  57314. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57315. -0.5, 0.5, 0, 1,
  57316. -0.5, -0.5, 0, 0,
  57317. 0.5, -0.5, 1, 0]);
  57318. // Buffers
  57319. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57320. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57321. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57322. // Update VAO
  57323. this._updateVAO = [];
  57324. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57325. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57326. // Render VAO
  57327. this._renderVAO = [];
  57328. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57329. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57330. // Links
  57331. this._sourceBuffer = this._buffer0;
  57332. this._targetBuffer = this._buffer1;
  57333. };
  57334. /** @hidden */
  57335. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57336. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57337. if (this._isBillboardBased) {
  57338. defines += "\n#define BILLBOARD";
  57339. }
  57340. if (this._colorGradientsTexture) {
  57341. defines += "\n#define COLORGRADIENTS";
  57342. }
  57343. if (this._sizeGradientsTexture) {
  57344. defines += "\n#define SIZEGRADIENTS";
  57345. }
  57346. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57347. return;
  57348. }
  57349. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  57350. if (this._sizeGradientsTexture) {
  57351. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialSize");
  57352. }
  57353. if (!this._colorGradientsTexture) {
  57354. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  57355. }
  57356. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  57357. if (!this._isBillboardBased) {
  57358. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  57359. }
  57360. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  57361. this._updateEffectOptions.defines = defines;
  57362. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57363. };
  57364. /** @hidden */
  57365. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57366. var defines = "";
  57367. if (this._scene.clipPlane) {
  57368. defines = "\n#define CLIPPLANE";
  57369. }
  57370. if (this._isBillboardBased) {
  57371. defines += "\n#define BILLBOARD";
  57372. }
  57373. if (this._colorGradientsTexture) {
  57374. defines += "\n#define COLORGRADIENTS";
  57375. }
  57376. if (this._renderEffect && this._renderEffect.defines === defines) {
  57377. return;
  57378. }
  57379. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler", "colorGradientSampler"], this._scene.getEngine(), defines);
  57380. };
  57381. /**
  57382. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57383. * @param preWarm defines if we are in the pre-warmimg phase
  57384. */
  57385. GPUParticleSystem.prototype.animate = function (preWarm) {
  57386. if (preWarm === void 0) { preWarm = false; }
  57387. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57388. this._actualFrame += this._timeDelta;
  57389. if (!this._stopped) {
  57390. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57391. this.stop();
  57392. }
  57393. }
  57394. };
  57395. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  57396. if (!this._sizeGradients || !this._sizeGradients.length || this._sizeGradientsTexture) {
  57397. return;
  57398. }
  57399. var textureWidth = 256;
  57400. var data = new Float32Array(textureWidth);
  57401. for (var x = 0; x < textureWidth; x++) {
  57402. var ratio = x / textureWidth;
  57403. BABYLON.Tools.GetCurrentGradient(ratio, this._sizeGradients, function (currentGradient, nextGradient, scale) {
  57404. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor, nextGradient.factor, scale);
  57405. });
  57406. }
  57407. this._sizeGradientsTexture = BABYLON.RawTexture.CreateRTexture(data, textureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57408. };
  57409. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  57410. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  57411. return;
  57412. }
  57413. var textureWidth = 256;
  57414. var data = new Uint8Array(textureWidth * 4);
  57415. var tmpColor = BABYLON.Tmp.Color4[0];
  57416. for (var x = 0; x < textureWidth; x++) {
  57417. var ratio = x / textureWidth;
  57418. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  57419. BABYLON.Color4.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  57420. data[x * 4] = tmpColor.r * 255;
  57421. data[x * 4 + 1] = tmpColor.g * 255;
  57422. data[x * 4 + 2] = tmpColor.b * 255;
  57423. data[x * 4 + 3] = tmpColor.a * 255;
  57424. });
  57425. }
  57426. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, textureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57427. };
  57428. /**
  57429. * Renders the particle system in its current state
  57430. * @param preWarm defines if the system should only update the particles but not render them
  57431. * @returns the current number of particles
  57432. */
  57433. GPUParticleSystem.prototype.render = function (preWarm) {
  57434. if (preWarm === void 0) { preWarm = false; }
  57435. if (!this._started) {
  57436. return 0;
  57437. }
  57438. this._createColorGradientTexture();
  57439. this._createSizeGradientTexture();
  57440. this._recreateUpdateEffect();
  57441. this._recreateRenderEffect();
  57442. if (!this.isReady()) {
  57443. return 0;
  57444. }
  57445. if (!preWarm) {
  57446. if (!this._preWarmDone && this.preWarmCycles) {
  57447. for (var index = 0; index < this.preWarmCycles; index++) {
  57448. this.animate(true);
  57449. this.render(true);
  57450. }
  57451. this._preWarmDone = true;
  57452. }
  57453. if (this._currentRenderId === this._scene.getRenderId()) {
  57454. return 0;
  57455. }
  57456. this._currentRenderId = this._scene.getRenderId();
  57457. }
  57458. // Get everything ready to render
  57459. this._initialize();
  57460. this._accumulatedCount += this.emitRate * this._timeDelta;
  57461. if (this._accumulatedCount > 1) {
  57462. var intPart = this._accumulatedCount | 0;
  57463. this._accumulatedCount -= intPart;
  57464. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  57465. }
  57466. if (!this._currentActiveCount) {
  57467. return 0;
  57468. }
  57469. // Enable update effect
  57470. this._engine.enableEffect(this._updateEffect);
  57471. this._engine.setState(false);
  57472. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57473. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57474. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57475. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57476. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  57477. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57478. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57479. if (!this._colorGradientsTexture) {
  57480. this._updateEffect.setDirectColor4("color1", this.color1);
  57481. this._updateEffect.setDirectColor4("color2", this.color2);
  57482. }
  57483. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57484. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  57485. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  57486. this._updateEffect.setVector3("gravity", this.gravity);
  57487. if (this._sizeGradientsTexture) {
  57488. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  57489. }
  57490. if (this.particleEmitterType) {
  57491. this.particleEmitterType.applyToShader(this._updateEffect);
  57492. }
  57493. var emitterWM;
  57494. if (this.emitter.position) {
  57495. var emitterMesh = this.emitter;
  57496. emitterWM = emitterMesh.getWorldMatrix();
  57497. }
  57498. else {
  57499. var emitterPosition = this.emitter;
  57500. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57501. }
  57502. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57503. // Bind source VAO
  57504. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57505. // Update
  57506. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57507. this._engine.setRasterizerState(false);
  57508. this._engine.beginTransformFeedback();
  57509. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57510. this._engine.endTransformFeedback();
  57511. this._engine.setRasterizerState(true);
  57512. this._engine.bindTransformFeedbackBuffer(null);
  57513. if (!preWarm) {
  57514. // Enable render effect
  57515. this._engine.enableEffect(this._renderEffect);
  57516. var viewMatrix = this._scene.getViewMatrix();
  57517. this._renderEffect.setMatrix("view", viewMatrix);
  57518. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57519. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57520. if (this._colorGradientsTexture) {
  57521. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  57522. }
  57523. else {
  57524. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57525. }
  57526. if (this._scene.clipPlane) {
  57527. var clipPlane = this._scene.clipPlane;
  57528. var invView = viewMatrix.clone();
  57529. invView.invert();
  57530. this._renderEffect.setMatrix("invView", invView);
  57531. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57532. }
  57533. // Draw order
  57534. switch (this.blendMode) {
  57535. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  57536. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57537. break;
  57538. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  57539. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57540. break;
  57541. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  57542. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57543. break;
  57544. }
  57545. if (this.forceDepthWrite) {
  57546. this._engine.setDepthWrite(true);
  57547. }
  57548. // Bind source VAO
  57549. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57550. // Render
  57551. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57552. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57553. }
  57554. // Switch VAOs
  57555. this._targetIndex++;
  57556. if (this._targetIndex === 2) {
  57557. this._targetIndex = 0;
  57558. }
  57559. // Switch buffers
  57560. var tmpBuffer = this._sourceBuffer;
  57561. this._sourceBuffer = this._targetBuffer;
  57562. this._targetBuffer = tmpBuffer;
  57563. return this._currentActiveCount;
  57564. };
  57565. /**
  57566. * Rebuilds the particle system
  57567. */
  57568. GPUParticleSystem.prototype.rebuild = function () {
  57569. this._initialize(true);
  57570. };
  57571. GPUParticleSystem.prototype._releaseBuffers = function () {
  57572. if (this._buffer0) {
  57573. this._buffer0.dispose();
  57574. this._buffer0 = null;
  57575. }
  57576. if (this._buffer1) {
  57577. this._buffer1.dispose();
  57578. this._buffer1 = null;
  57579. }
  57580. if (this._spriteBuffer) {
  57581. this._spriteBuffer.dispose();
  57582. this._spriteBuffer = null;
  57583. }
  57584. };
  57585. GPUParticleSystem.prototype._releaseVAOs = function () {
  57586. if (!this._updateVAO) {
  57587. return;
  57588. }
  57589. for (var index = 0; index < this._updateVAO.length; index++) {
  57590. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57591. }
  57592. this._updateVAO = [];
  57593. for (var index = 0; index < this._renderVAO.length; index++) {
  57594. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57595. }
  57596. this._renderVAO = [];
  57597. };
  57598. /**
  57599. * Disposes the particle system and free the associated resources
  57600. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57601. */
  57602. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57603. if (disposeTexture === void 0) { disposeTexture = true; }
  57604. var index = this._scene.particleSystems.indexOf(this);
  57605. if (index > -1) {
  57606. this._scene.particleSystems.splice(index, 1);
  57607. }
  57608. this._releaseBuffers();
  57609. this._releaseVAOs();
  57610. if (this._colorGradientsTexture) {
  57611. this._colorGradientsTexture.dispose();
  57612. this._colorGradientsTexture = null;
  57613. }
  57614. if (this._sizeGradientsTexture) {
  57615. this._sizeGradientsTexture.dispose();
  57616. this._sizeGradientsTexture = null;
  57617. }
  57618. if (this._randomTexture) {
  57619. this._randomTexture.dispose();
  57620. this._randomTexture = null;
  57621. }
  57622. if (this._randomTexture2) {
  57623. this._randomTexture2.dispose();
  57624. this._randomTexture2 = null;
  57625. }
  57626. if (disposeTexture && this.particleTexture) {
  57627. this.particleTexture.dispose();
  57628. this.particleTexture = null;
  57629. }
  57630. // Callback
  57631. this.onDisposeObservable.notifyObservers(this);
  57632. this.onDisposeObservable.clear();
  57633. };
  57634. /**
  57635. * Clones the particle system.
  57636. * @param name The name of the cloned object
  57637. * @param newEmitter The new emitter to use
  57638. * @returns the cloned particle system
  57639. */
  57640. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57641. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57642. BABYLON.Tools.DeepCopy(this, result);
  57643. if (newEmitter === undefined) {
  57644. newEmitter = this.emitter;
  57645. }
  57646. result.emitter = newEmitter;
  57647. if (this.particleTexture) {
  57648. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57649. }
  57650. return result;
  57651. };
  57652. /**
  57653. * Serializes the particle system to a JSON object.
  57654. * @returns the JSON object
  57655. */
  57656. GPUParticleSystem.prototype.serialize = function () {
  57657. var serializationObject = {};
  57658. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  57659. return serializationObject;
  57660. };
  57661. /**
  57662. * Parses a JSON object to create a GPU particle system.
  57663. * @param parsedParticleSystem The JSON object to parse
  57664. * @param scene The scene to create the particle system in
  57665. * @param rootUrl The root url to use to load external dependencies like texture
  57666. * @returns the parsed GPU particle system
  57667. */
  57668. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57669. var name = parsedParticleSystem.name;
  57670. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57671. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57672. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  57673. return particleSystem;
  57674. };
  57675. return GPUParticleSystem;
  57676. }());
  57677. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57678. })(BABYLON || (BABYLON = {}));
  57679. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57680. var BABYLON;
  57681. (function (BABYLON) {
  57682. /**
  57683. * Represents one particle of a solid particle system.
  57684. */
  57685. var SolidParticle = /** @class */ (function () {
  57686. /**
  57687. * Creates a Solid Particle object.
  57688. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57689. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57690. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57691. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57692. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57693. * @param shapeId (integer) is the model shape identifier in the SPS.
  57694. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57695. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57696. */
  57697. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57698. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57699. /**
  57700. * particle global index
  57701. */
  57702. this.idx = 0;
  57703. /**
  57704. * The color of the particle
  57705. */
  57706. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57707. /**
  57708. * The world space position of the particle.
  57709. */
  57710. this.position = BABYLON.Vector3.Zero();
  57711. /**
  57712. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57713. */
  57714. this.rotation = BABYLON.Vector3.Zero();
  57715. /**
  57716. * The scaling of the particle.
  57717. */
  57718. this.scaling = BABYLON.Vector3.One();
  57719. /**
  57720. * The uvs of the particle.
  57721. */
  57722. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57723. /**
  57724. * The current speed of the particle.
  57725. */
  57726. this.velocity = BABYLON.Vector3.Zero();
  57727. /**
  57728. * The pivot point in the particle local space.
  57729. */
  57730. this.pivot = BABYLON.Vector3.Zero();
  57731. /**
  57732. * Must the particle be translated from its pivot point in its local space ?
  57733. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57734. * Default : false
  57735. */
  57736. this.translateFromPivot = false;
  57737. /**
  57738. * Is the particle active or not ?
  57739. */
  57740. this.alive = true;
  57741. /**
  57742. * Is the particle visible or not ?
  57743. */
  57744. this.isVisible = true;
  57745. /**
  57746. * Index of this particle in the global "positions" array (Internal use)
  57747. */
  57748. this._pos = 0;
  57749. /**
  57750. * Index of this particle in the global "indices" array (Internal use)
  57751. */
  57752. this._ind = 0;
  57753. /**
  57754. * ModelShape id of this particle
  57755. */
  57756. this.shapeId = 0;
  57757. /**
  57758. * Index of the particle in its shape id (Internal use)
  57759. */
  57760. this.idxInShape = 0;
  57761. /**
  57762. * Still set as invisible in order to skip useless computations (Internal use)
  57763. */
  57764. this._stillInvisible = false;
  57765. /**
  57766. * Last computed particle rotation matrix
  57767. */
  57768. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57769. /**
  57770. * Parent particle Id, if any.
  57771. * Default null.
  57772. */
  57773. this.parentId = null;
  57774. /**
  57775. * Internal global position in the SPS.
  57776. */
  57777. this._globalPosition = BABYLON.Vector3.Zero();
  57778. this.idx = particleIndex;
  57779. this._pos = positionIndex;
  57780. this._ind = indiceIndex;
  57781. this._model = model;
  57782. this.shapeId = shapeId;
  57783. this.idxInShape = idxInShape;
  57784. this._sps = sps;
  57785. if (modelBoundingInfo) {
  57786. this._modelBoundingInfo = modelBoundingInfo;
  57787. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57788. }
  57789. }
  57790. Object.defineProperty(SolidParticle.prototype, "scale", {
  57791. /**
  57792. * Legacy support, changed scale to scaling
  57793. */
  57794. get: function () {
  57795. return this.scaling;
  57796. },
  57797. /**
  57798. * Legacy support, changed scale to scaling
  57799. */
  57800. set: function (scale) {
  57801. this.scaling = scale;
  57802. },
  57803. enumerable: true,
  57804. configurable: true
  57805. });
  57806. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57807. /**
  57808. * Legacy support, changed quaternion to rotationQuaternion
  57809. */
  57810. get: function () {
  57811. return this.rotationQuaternion;
  57812. },
  57813. /**
  57814. * Legacy support, changed quaternion to rotationQuaternion
  57815. */
  57816. set: function (q) {
  57817. this.rotationQuaternion = q;
  57818. },
  57819. enumerable: true,
  57820. configurable: true
  57821. });
  57822. /**
  57823. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57824. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57825. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57826. * @returns true if it intersects
  57827. */
  57828. SolidParticle.prototype.intersectsMesh = function (target) {
  57829. if (!this._boundingInfo || !target._boundingInfo) {
  57830. return false;
  57831. }
  57832. if (this._sps._bSphereOnly) {
  57833. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57834. }
  57835. return this._boundingInfo.intersects(target._boundingInfo, false);
  57836. };
  57837. return SolidParticle;
  57838. }());
  57839. BABYLON.SolidParticle = SolidParticle;
  57840. /**
  57841. * Represents the shape of the model used by one particle of a solid particle system.
  57842. * SPS internal tool, don't use it manually.
  57843. */
  57844. var ModelShape = /** @class */ (function () {
  57845. /**
  57846. * 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.
  57847. * SPS internal tool, don't use it manually.
  57848. * @hidden
  57849. */
  57850. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57851. /**
  57852. * length of the shape in the model indices array (internal use)
  57853. */
  57854. this._indicesLength = 0;
  57855. this.shapeID = id;
  57856. this._shape = shape;
  57857. this._indicesLength = indicesLength;
  57858. this._shapeUV = shapeUV;
  57859. this._positionFunction = posFunction;
  57860. this._vertexFunction = vtxFunction;
  57861. }
  57862. return ModelShape;
  57863. }());
  57864. BABYLON.ModelShape = ModelShape;
  57865. /**
  57866. * Represents a Depth Sorted Particle in the solid particle system.
  57867. */
  57868. var DepthSortedParticle = /** @class */ (function () {
  57869. function DepthSortedParticle() {
  57870. /**
  57871. * Index of the particle in the "indices" array
  57872. */
  57873. this.ind = 0;
  57874. /**
  57875. * Length of the particle shape in the "indices" array
  57876. */
  57877. this.indicesLength = 0;
  57878. /**
  57879. * Squared distance from the particle to the camera
  57880. */
  57881. this.sqDistance = 0.0;
  57882. }
  57883. return DepthSortedParticle;
  57884. }());
  57885. BABYLON.DepthSortedParticle = DepthSortedParticle;
  57886. })(BABYLON || (BABYLON = {}));
  57887. //# sourceMappingURL=babylon.solidParticle.js.map
  57888. var BABYLON;
  57889. (function (BABYLON) {
  57890. /**
  57891. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  57892. *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.
  57893. * The SPS is also a particle system. It provides some methods to manage the particles.
  57894. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  57895. *
  57896. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57897. */
  57898. var SolidParticleSystem = /** @class */ (function () {
  57899. /**
  57900. * Creates a SPS (Solid Particle System) object.
  57901. * @param name (String) is the SPS name, this will be the underlying mesh name.
  57902. * @param scene (Scene) is the scene in which the SPS is added.
  57903. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  57904. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  57905. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  57906. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  57907. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  57908. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  57909. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  57910. */
  57911. function SolidParticleSystem(name, scene, options) {
  57912. /**
  57913. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57914. * Example : var p = SPS.particles[i];
  57915. */
  57916. this.particles = new Array();
  57917. /**
  57918. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57919. */
  57920. this.nbParticles = 0;
  57921. /**
  57922. * If the particles must ever face the camera (default false). Useful for planar particles.
  57923. */
  57924. this.billboard = false;
  57925. /**
  57926. * Recompute normals when adding a shape
  57927. */
  57928. this.recomputeNormals = true;
  57929. /**
  57930. * This a counter ofr your own usage. It's not set by any SPS functions.
  57931. */
  57932. this.counter = 0;
  57933. /**
  57934. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57935. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57936. */
  57937. this.vars = {};
  57938. /**
  57939. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  57940. */
  57941. this._bSphereOnly = false;
  57942. /**
  57943. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  57944. */
  57945. this._bSphereRadiusFactor = 1.0;
  57946. this._positions = new Array();
  57947. this._indices = new Array();
  57948. this._normals = new Array();
  57949. this._colors = new Array();
  57950. this._uvs = new Array();
  57951. this._index = 0; // indices index
  57952. this._updatable = true;
  57953. this._pickable = false;
  57954. this._isVisibilityBoxLocked = false;
  57955. this._alwaysVisible = false;
  57956. this._depthSort = false;
  57957. this._shapeCounter = 0;
  57958. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  57959. this._color = new BABYLON.Color4(0, 0, 0, 0);
  57960. this._computeParticleColor = true;
  57961. this._computeParticleTexture = true;
  57962. this._computeParticleRotation = true;
  57963. this._computeParticleVertex = false;
  57964. this._computeBoundingBox = false;
  57965. this._depthSortParticles = true;
  57966. this._cam_axisZ = BABYLON.Vector3.Zero();
  57967. this._cam_axisY = BABYLON.Vector3.Zero();
  57968. this._cam_axisX = BABYLON.Vector3.Zero();
  57969. this._axisZ = BABYLON.Axis.Z;
  57970. this._camDir = BABYLON.Vector3.Zero();
  57971. this._camInvertedPosition = BABYLON.Vector3.Zero();
  57972. this._rotMatrix = new BABYLON.Matrix();
  57973. this._invertMatrix = new BABYLON.Matrix();
  57974. this._rotated = BABYLON.Vector3.Zero();
  57975. this._quaternion = new BABYLON.Quaternion();
  57976. this._vertex = BABYLON.Vector3.Zero();
  57977. this._normal = BABYLON.Vector3.Zero();
  57978. this._yaw = 0.0;
  57979. this._pitch = 0.0;
  57980. this._roll = 0.0;
  57981. this._halfroll = 0.0;
  57982. this._halfpitch = 0.0;
  57983. this._halfyaw = 0.0;
  57984. this._sinRoll = 0.0;
  57985. this._cosRoll = 0.0;
  57986. this._sinPitch = 0.0;
  57987. this._cosPitch = 0.0;
  57988. this._sinYaw = 0.0;
  57989. this._cosYaw = 0.0;
  57990. this._mustUnrotateFixedNormals = false;
  57991. this._minimum = BABYLON.Vector3.Zero();
  57992. this._maximum = BABYLON.Vector3.Zero();
  57993. this._minBbox = BABYLON.Vector3.Zero();
  57994. this._maxBbox = BABYLON.Vector3.Zero();
  57995. this._particlesIntersect = false;
  57996. this._depthSortFunction = function (p1, p2) {
  57997. return (p2.sqDistance - p1.sqDistance);
  57998. };
  57999. this._needs32Bits = false;
  58000. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58001. this._scaledPivot = BABYLON.Vector3.Zero();
  58002. this._particleHasParent = false;
  58003. this.name = name;
  58004. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58005. this._camera = scene.activeCamera;
  58006. this._pickable = options ? options.isPickable : false;
  58007. this._depthSort = options ? options.enableDepthSort : false;
  58008. this._particlesIntersect = options ? options.particleIntersection : false;
  58009. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58010. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58011. if (options && options.updatable !== undefined) {
  58012. this._updatable = options.updatable;
  58013. }
  58014. else {
  58015. this._updatable = true;
  58016. }
  58017. if (this._pickable) {
  58018. this.pickedParticles = [];
  58019. }
  58020. if (this._depthSort) {
  58021. this.depthSortedParticles = [];
  58022. }
  58023. }
  58024. /**
  58025. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58026. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58027. * @returns the created mesh
  58028. */
  58029. SolidParticleSystem.prototype.buildMesh = function () {
  58030. if (this.nbParticles === 0) {
  58031. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58032. this.addShape(triangle, 1);
  58033. triangle.dispose();
  58034. }
  58035. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58036. this._positions32 = new Float32Array(this._positions);
  58037. this._uvs32 = new Float32Array(this._uvs);
  58038. this._colors32 = new Float32Array(this._colors);
  58039. if (this.recomputeNormals) {
  58040. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58041. }
  58042. this._normals32 = new Float32Array(this._normals);
  58043. this._fixedNormal32 = new Float32Array(this._normals);
  58044. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58045. this._unrotateFixedNormals();
  58046. }
  58047. var vertexData = new BABYLON.VertexData();
  58048. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58049. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58050. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58051. if (this._uvs32.length > 0) {
  58052. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58053. }
  58054. if (this._colors32.length > 0) {
  58055. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58056. }
  58057. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58058. vertexData.applyToMesh(mesh, this._updatable);
  58059. this.mesh = mesh;
  58060. this.mesh.isPickable = this._pickable;
  58061. // free memory
  58062. if (!this._depthSort) {
  58063. this._indices = null;
  58064. }
  58065. this._positions = null;
  58066. this._normals = null;
  58067. this._uvs = null;
  58068. this._colors = null;
  58069. if (!this._updatable) {
  58070. this.particles.length = 0;
  58071. }
  58072. return mesh;
  58073. };
  58074. /**
  58075. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58076. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58077. * Thus the particles generated from `digest()` have their property `position` set yet.
  58078. * @param mesh ( Mesh ) is the mesh to be digested
  58079. * @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
  58080. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58081. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58082. * @returns the current SPS
  58083. */
  58084. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58085. var size = (options && options.facetNb) || 1;
  58086. var number = (options && options.number) || 0;
  58087. var delta = (options && options.delta) || 0;
  58088. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58089. var meshInd = mesh.getIndices();
  58090. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58091. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58092. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58093. var f = 0; // facet counter
  58094. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58095. // compute size from number
  58096. if (number) {
  58097. number = (number > totalFacets) ? totalFacets : number;
  58098. size = Math.round(totalFacets / number);
  58099. delta = 0;
  58100. }
  58101. else {
  58102. size = (size > totalFacets) ? totalFacets : size;
  58103. }
  58104. var facetPos = []; // submesh positions
  58105. var facetInd = []; // submesh indices
  58106. var facetUV = []; // submesh UV
  58107. var facetCol = []; // submesh colors
  58108. var barycenter = BABYLON.Vector3.Zero();
  58109. var sizeO = size;
  58110. while (f < totalFacets) {
  58111. size = sizeO + Math.floor((1 + delta) * Math.random());
  58112. if (f > totalFacets - size) {
  58113. size = totalFacets - f;
  58114. }
  58115. // reset temp arrays
  58116. facetPos.length = 0;
  58117. facetInd.length = 0;
  58118. facetUV.length = 0;
  58119. facetCol.length = 0;
  58120. // iterate over "size" facets
  58121. var fi = 0;
  58122. for (var j = f * 3; j < (f + size) * 3; j++) {
  58123. facetInd.push(fi);
  58124. var i = meshInd[j];
  58125. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58126. if (meshUV) {
  58127. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58128. }
  58129. if (meshCol) {
  58130. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58131. }
  58132. fi++;
  58133. }
  58134. // create a model shape for each single particle
  58135. var idx = this.nbParticles;
  58136. var shape = this._posToShape(facetPos);
  58137. var shapeUV = this._uvsToShapeUV(facetUV);
  58138. // compute the barycenter of the shape
  58139. var v;
  58140. for (v = 0; v < shape.length; v++) {
  58141. barycenter.addInPlace(shape[v]);
  58142. }
  58143. barycenter.scaleInPlace(1 / shape.length);
  58144. // shift the shape from its barycenter to the origin
  58145. for (v = 0; v < shape.length; v++) {
  58146. shape[v].subtractInPlace(barycenter);
  58147. }
  58148. var bInfo;
  58149. if (this._particlesIntersect) {
  58150. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58151. }
  58152. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58153. // add the particle in the SPS
  58154. var currentPos = this._positions.length;
  58155. var currentInd = this._indices.length;
  58156. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58157. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58158. // initialize the particle position
  58159. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58160. this._index += shape.length;
  58161. idx++;
  58162. this.nbParticles++;
  58163. this._shapeCounter++;
  58164. f += size;
  58165. }
  58166. return this;
  58167. };
  58168. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58169. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58170. var index = 0;
  58171. var idx = 0;
  58172. for (var p = 0; p < this.particles.length; p++) {
  58173. this._particle = this.particles[p];
  58174. this._shape = this._particle._model._shape;
  58175. if (this._particle.rotationQuaternion) {
  58176. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58177. }
  58178. else {
  58179. this._yaw = this._particle.rotation.y;
  58180. this._pitch = this._particle.rotation.x;
  58181. this._roll = this._particle.rotation.z;
  58182. this._quaternionRotationYPR();
  58183. }
  58184. this._quaternionToRotationMatrix();
  58185. this._rotMatrix.invertToRef(this._invertMatrix);
  58186. for (var pt = 0; pt < this._shape.length; pt++) {
  58187. idx = index + pt * 3;
  58188. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58189. this._fixedNormal32[idx] = this._normal.x;
  58190. this._fixedNormal32[idx + 1] = this._normal.y;
  58191. this._fixedNormal32[idx + 2] = this._normal.z;
  58192. }
  58193. index = idx + 3;
  58194. }
  58195. };
  58196. //reset copy
  58197. SolidParticleSystem.prototype._resetCopy = function () {
  58198. this._copy.position.x = 0;
  58199. this._copy.position.y = 0;
  58200. this._copy.position.z = 0;
  58201. this._copy.rotation.x = 0;
  58202. this._copy.rotation.y = 0;
  58203. this._copy.rotation.z = 0;
  58204. this._copy.rotationQuaternion = null;
  58205. this._copy.scaling.x = 1.0;
  58206. this._copy.scaling.y = 1.0;
  58207. this._copy.scaling.z = 1.0;
  58208. this._copy.uvs.x = 0;
  58209. this._copy.uvs.y = 0;
  58210. this._copy.uvs.z = 1.0;
  58211. this._copy.uvs.w = 1.0;
  58212. this._copy.color = null;
  58213. this._copy.translateFromPivot = false;
  58214. };
  58215. // _meshBuilder : inserts the shape model in the global SPS mesh
  58216. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58217. var i;
  58218. var u = 0;
  58219. var c = 0;
  58220. var n = 0;
  58221. this._resetCopy();
  58222. if (options && options.positionFunction) { // call to custom positionFunction
  58223. options.positionFunction(this._copy, idx, idxInShape);
  58224. this._mustUnrotateFixedNormals = true;
  58225. }
  58226. if (this._copy.rotationQuaternion) {
  58227. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58228. }
  58229. else {
  58230. this._yaw = this._copy.rotation.y;
  58231. this._pitch = this._copy.rotation.x;
  58232. this._roll = this._copy.rotation.z;
  58233. this._quaternionRotationYPR();
  58234. }
  58235. this._quaternionToRotationMatrix();
  58236. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58237. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58238. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58239. if (this._copy.translateFromPivot) {
  58240. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58241. }
  58242. else {
  58243. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58244. }
  58245. for (i = 0; i < shape.length; i++) {
  58246. this._vertex.x = shape[i].x;
  58247. this._vertex.y = shape[i].y;
  58248. this._vertex.z = shape[i].z;
  58249. if (options && options.vertexFunction) {
  58250. options.vertexFunction(this._copy, this._vertex, i);
  58251. }
  58252. this._vertex.x *= this._copy.scaling.x;
  58253. this._vertex.y *= this._copy.scaling.y;
  58254. this._vertex.z *= this._copy.scaling.z;
  58255. this._vertex.x -= this._scaledPivot.x;
  58256. this._vertex.y -= this._scaledPivot.y;
  58257. this._vertex.z -= this._scaledPivot.z;
  58258. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58259. this._rotated.addInPlace(this._pivotBackTranslation);
  58260. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58261. if (meshUV) {
  58262. 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);
  58263. u += 2;
  58264. }
  58265. if (this._copy.color) {
  58266. this._color = this._copy.color;
  58267. }
  58268. else if (meshCol && meshCol[c] !== undefined) {
  58269. this._color.r = meshCol[c];
  58270. this._color.g = meshCol[c + 1];
  58271. this._color.b = meshCol[c + 2];
  58272. this._color.a = meshCol[c + 3];
  58273. }
  58274. else {
  58275. this._color.r = 1.0;
  58276. this._color.g = 1.0;
  58277. this._color.b = 1.0;
  58278. this._color.a = 1.0;
  58279. }
  58280. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58281. c += 4;
  58282. if (!this.recomputeNormals && meshNor) {
  58283. this._normal.x = meshNor[n];
  58284. this._normal.y = meshNor[n + 1];
  58285. this._normal.z = meshNor[n + 2];
  58286. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58287. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58288. n += 3;
  58289. }
  58290. }
  58291. for (i = 0; i < meshInd.length; i++) {
  58292. var current_ind = p + meshInd[i];
  58293. indices.push(current_ind);
  58294. if (current_ind > 65535) {
  58295. this._needs32Bits = true;
  58296. }
  58297. }
  58298. if (this._pickable) {
  58299. var nbfaces = meshInd.length / 3;
  58300. for (i = 0; i < nbfaces; i++) {
  58301. this.pickedParticles.push({ idx: idx, faceId: i });
  58302. }
  58303. }
  58304. if (this._depthSort) {
  58305. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58306. }
  58307. return this._copy;
  58308. };
  58309. // returns a shape array from positions array
  58310. SolidParticleSystem.prototype._posToShape = function (positions) {
  58311. var shape = [];
  58312. for (var i = 0; i < positions.length; i += 3) {
  58313. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58314. }
  58315. return shape;
  58316. };
  58317. // returns a shapeUV array from a Vector4 uvs
  58318. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58319. var shapeUV = [];
  58320. if (uvs) {
  58321. for (var i = 0; i < uvs.length; i++)
  58322. shapeUV.push(uvs[i]);
  58323. }
  58324. return shapeUV;
  58325. };
  58326. // adds a new particle object in the particles array
  58327. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58328. if (bInfo === void 0) { bInfo = null; }
  58329. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58330. this.particles.push(sp);
  58331. return sp;
  58332. };
  58333. /**
  58334. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58335. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58336. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58337. * @param nb (positive integer) the number of particles to be created from this model
  58338. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58339. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58340. * @returns the number of shapes in the system
  58341. */
  58342. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58343. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58344. var meshInd = mesh.getIndices();
  58345. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58346. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58347. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58348. var bbInfo;
  58349. if (this._particlesIntersect) {
  58350. bbInfo = mesh.getBoundingInfo();
  58351. }
  58352. var shape = this._posToShape(meshPos);
  58353. var shapeUV = this._uvsToShapeUV(meshUV);
  58354. var posfunc = options ? options.positionFunction : null;
  58355. var vtxfunc = options ? options.vertexFunction : null;
  58356. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58357. // particles
  58358. var sp;
  58359. var currentCopy;
  58360. var idx = this.nbParticles;
  58361. for (var i = 0; i < nb; i++) {
  58362. var currentPos = this._positions.length;
  58363. var currentInd = this._indices.length;
  58364. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58365. if (this._updatable) {
  58366. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58367. sp.position.copyFrom(currentCopy.position);
  58368. sp.rotation.copyFrom(currentCopy.rotation);
  58369. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58370. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58371. }
  58372. if (currentCopy.color && sp.color) {
  58373. sp.color.copyFrom(currentCopy.color);
  58374. }
  58375. sp.scaling.copyFrom(currentCopy.scaling);
  58376. sp.uvs.copyFrom(currentCopy.uvs);
  58377. }
  58378. this._index += shape.length;
  58379. idx++;
  58380. }
  58381. this.nbParticles += nb;
  58382. this._shapeCounter++;
  58383. return this._shapeCounter - 1;
  58384. };
  58385. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58386. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58387. this._resetCopy();
  58388. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58389. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58390. }
  58391. if (this._copy.rotationQuaternion) {
  58392. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58393. }
  58394. else {
  58395. this._yaw = this._copy.rotation.y;
  58396. this._pitch = this._copy.rotation.x;
  58397. this._roll = this._copy.rotation.z;
  58398. this._quaternionRotationYPR();
  58399. }
  58400. this._quaternionToRotationMatrix();
  58401. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58402. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58403. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58404. if (this._copy.translateFromPivot) {
  58405. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58406. }
  58407. else {
  58408. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58409. }
  58410. this._shape = particle._model._shape;
  58411. for (var pt = 0; pt < this._shape.length; pt++) {
  58412. this._vertex.x = this._shape[pt].x;
  58413. this._vertex.y = this._shape[pt].y;
  58414. this._vertex.z = this._shape[pt].z;
  58415. if (particle._model._vertexFunction) {
  58416. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58417. }
  58418. this._vertex.x *= this._copy.scaling.x;
  58419. this._vertex.y *= this._copy.scaling.y;
  58420. this._vertex.z *= this._copy.scaling.z;
  58421. this._vertex.x -= this._scaledPivot.x;
  58422. this._vertex.y -= this._scaledPivot.y;
  58423. this._vertex.z -= this._scaledPivot.z;
  58424. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58425. this._rotated.addInPlace(this._pivotBackTranslation);
  58426. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58427. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58428. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58429. }
  58430. particle.position.x = 0.0;
  58431. particle.position.y = 0.0;
  58432. particle.position.z = 0.0;
  58433. particle.rotation.x = 0.0;
  58434. particle.rotation.y = 0.0;
  58435. particle.rotation.z = 0.0;
  58436. particle.rotationQuaternion = null;
  58437. particle.scaling.x = 1.0;
  58438. particle.scaling.y = 1.0;
  58439. particle.scaling.z = 1.0;
  58440. particle.uvs.x = 0.0;
  58441. particle.uvs.y = 0.0;
  58442. particle.uvs.z = 1.0;
  58443. particle.uvs.w = 1.0;
  58444. particle.pivot.x = 0.0;
  58445. particle.pivot.y = 0.0;
  58446. particle.pivot.z = 0.0;
  58447. particle.translateFromPivot = false;
  58448. particle.parentId = null;
  58449. };
  58450. /**
  58451. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58452. * @returns the SPS.
  58453. */
  58454. SolidParticleSystem.prototype.rebuildMesh = function () {
  58455. for (var p = 0; p < this.particles.length; p++) {
  58456. this._rebuildParticle(this.particles[p]);
  58457. }
  58458. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58459. return this;
  58460. };
  58461. /**
  58462. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58463. * This method calls `updateParticle()` for each particle of the SPS.
  58464. * For an animated SPS, it is usually called within the render loop.
  58465. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58466. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58467. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58468. * @returns the SPS.
  58469. */
  58470. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58471. if (start === void 0) { start = 0; }
  58472. if (end === void 0) { end = this.nbParticles - 1; }
  58473. if (update === void 0) { update = true; }
  58474. if (!this._updatable) {
  58475. return this;
  58476. }
  58477. // custom beforeUpdate
  58478. this.beforeUpdateParticles(start, end, update);
  58479. this._cam_axisX.x = 1.0;
  58480. this._cam_axisX.y = 0.0;
  58481. this._cam_axisX.z = 0.0;
  58482. this._cam_axisY.x = 0.0;
  58483. this._cam_axisY.y = 1.0;
  58484. this._cam_axisY.z = 0.0;
  58485. this._cam_axisZ.x = 0.0;
  58486. this._cam_axisZ.y = 0.0;
  58487. this._cam_axisZ.z = 1.0;
  58488. // cases when the World Matrix is to be computed first
  58489. if (this.billboard || this._depthSort) {
  58490. this.mesh.computeWorldMatrix(true);
  58491. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58492. }
  58493. // if the particles will always face the camera
  58494. if (this.billboard) {
  58495. // compute the camera position and un-rotate it by the current mesh rotation
  58496. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58497. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58498. this._cam_axisZ.normalize();
  58499. // same for camera up vector extracted from the cam view matrix
  58500. var view = this._camera.getViewMatrix(true);
  58501. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58502. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58503. this._cam_axisY.normalize();
  58504. this._cam_axisX.normalize();
  58505. }
  58506. // if depthSort, compute the camera global position in the mesh local system
  58507. if (this._depthSort) {
  58508. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58509. }
  58510. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58511. var idx = 0; // current position index in the global array positions32
  58512. var index = 0; // position start index in the global array positions32 of the current particle
  58513. var colidx = 0; // current color index in the global array colors32
  58514. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58515. var uvidx = 0; // current uv index in the global array uvs32
  58516. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58517. var pt = 0; // current index in the particle model shape
  58518. if (this.mesh.isFacetDataEnabled) {
  58519. this._computeBoundingBox = true;
  58520. }
  58521. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58522. if (this._computeBoundingBox) {
  58523. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58524. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58525. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58526. }
  58527. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58528. if (this.mesh._boundingInfo) {
  58529. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58530. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58531. }
  58532. }
  58533. }
  58534. // particle loop
  58535. index = this.particles[start]._pos;
  58536. var vpos = (index / 3) | 0;
  58537. colorIndex = vpos * 4;
  58538. uvIndex = vpos * 2;
  58539. for (var p = start; p <= end; p++) {
  58540. this._particle = this.particles[p];
  58541. this._shape = this._particle._model._shape;
  58542. this._shapeUV = this._particle._model._shapeUV;
  58543. // call to custom user function to update the particle properties
  58544. this.updateParticle(this._particle);
  58545. // camera-particle distance for depth sorting
  58546. if (this._depthSort && this._depthSortParticles) {
  58547. var dsp = this.depthSortedParticles[p];
  58548. dsp.ind = this._particle._ind;
  58549. dsp.indicesLength = this._particle._model._indicesLength;
  58550. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58551. }
  58552. // skip the computations for inactive or already invisible particles
  58553. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58554. // increment indexes for the next particle
  58555. pt = this._shape.length;
  58556. index += pt * 3;
  58557. colorIndex += pt * 4;
  58558. uvIndex += pt * 2;
  58559. continue;
  58560. }
  58561. if (this._particle.isVisible) {
  58562. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58563. this._particleHasParent = (this._particle.parentId !== null);
  58564. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58565. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58566. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58567. // particle rotation matrix
  58568. if (this.billboard) {
  58569. this._particle.rotation.x = 0.0;
  58570. this._particle.rotation.y = 0.0;
  58571. }
  58572. if (this._computeParticleRotation || this.billboard) {
  58573. if (this._particle.rotationQuaternion) {
  58574. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58575. }
  58576. else {
  58577. this._yaw = this._particle.rotation.y;
  58578. this._pitch = this._particle.rotation.x;
  58579. this._roll = this._particle.rotation.z;
  58580. this._quaternionRotationYPR();
  58581. }
  58582. this._quaternionToRotationMatrix();
  58583. }
  58584. if (this._particleHasParent) {
  58585. this._parent = this.particles[this._particle.parentId];
  58586. 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];
  58587. 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];
  58588. 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];
  58589. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58590. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58591. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58592. if (this._computeParticleRotation || this.billboard) {
  58593. 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];
  58594. 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];
  58595. 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];
  58596. 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];
  58597. 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];
  58598. 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];
  58599. 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];
  58600. 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];
  58601. 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];
  58602. }
  58603. }
  58604. else {
  58605. this._particle._globalPosition.x = this._particle.position.x;
  58606. this._particle._globalPosition.y = this._particle.position.y;
  58607. this._particle._globalPosition.z = this._particle.position.z;
  58608. if (this._computeParticleRotation || this.billboard) {
  58609. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58610. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58611. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58612. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58613. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58614. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58615. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58616. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58617. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58618. }
  58619. }
  58620. if (this._particle.translateFromPivot) {
  58621. this._pivotBackTranslation.x = 0.0;
  58622. this._pivotBackTranslation.y = 0.0;
  58623. this._pivotBackTranslation.z = 0.0;
  58624. }
  58625. else {
  58626. this._pivotBackTranslation.x = this._scaledPivot.x;
  58627. this._pivotBackTranslation.y = this._scaledPivot.y;
  58628. this._pivotBackTranslation.z = this._scaledPivot.z;
  58629. }
  58630. // particle vertex loop
  58631. for (pt = 0; pt < this._shape.length; pt++) {
  58632. idx = index + pt * 3;
  58633. colidx = colorIndex + pt * 4;
  58634. uvidx = uvIndex + pt * 2;
  58635. this._vertex.x = this._shape[pt].x;
  58636. this._vertex.y = this._shape[pt].y;
  58637. this._vertex.z = this._shape[pt].z;
  58638. if (this._computeParticleVertex) {
  58639. this.updateParticleVertex(this._particle, this._vertex, pt);
  58640. }
  58641. // positions
  58642. this._vertex.x *= this._particle.scaling.x;
  58643. this._vertex.y *= this._particle.scaling.y;
  58644. this._vertex.z *= this._particle.scaling.z;
  58645. this._vertex.x -= this._scaledPivot.x;
  58646. this._vertex.y -= this._scaledPivot.y;
  58647. this._vertex.z -= this._scaledPivot.z;
  58648. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58649. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58650. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58651. this._rotated.x += this._pivotBackTranslation.x;
  58652. this._rotated.y += this._pivotBackTranslation.y;
  58653. this._rotated.z += this._pivotBackTranslation.z;
  58654. 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;
  58655. 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;
  58656. 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;
  58657. if (this._computeBoundingBox) {
  58658. if (this._positions32[idx] < this._minimum.x) {
  58659. this._minimum.x = this._positions32[idx];
  58660. }
  58661. if (this._positions32[idx] > this._maximum.x) {
  58662. this._maximum.x = this._positions32[idx];
  58663. }
  58664. if (this._positions32[idx + 1] < this._minimum.y) {
  58665. this._minimum.y = this._positions32[idx + 1];
  58666. }
  58667. if (this._positions32[idx + 1] > this._maximum.y) {
  58668. this._maximum.y = this._positions32[idx + 1];
  58669. }
  58670. if (this._positions32[idx + 2] < this._minimum.z) {
  58671. this._minimum.z = this._positions32[idx + 2];
  58672. }
  58673. if (this._positions32[idx + 2] > this._maximum.z) {
  58674. this._maximum.z = this._positions32[idx + 2];
  58675. }
  58676. }
  58677. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58678. if (!this._computeParticleVertex) {
  58679. this._normal.x = this._fixedNormal32[idx];
  58680. this._normal.y = this._fixedNormal32[idx + 1];
  58681. this._normal.z = this._fixedNormal32[idx + 2];
  58682. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58683. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58684. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58685. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58686. 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;
  58687. 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;
  58688. }
  58689. if (this._computeParticleColor && this._particle.color) {
  58690. this._colors32[colidx] = this._particle.color.r;
  58691. this._colors32[colidx + 1] = this._particle.color.g;
  58692. this._colors32[colidx + 2] = this._particle.color.b;
  58693. this._colors32[colidx + 3] = this._particle.color.a;
  58694. }
  58695. if (this._computeParticleTexture) {
  58696. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58697. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58698. }
  58699. }
  58700. }
  58701. // particle just set invisible : scaled to zero and positioned at the origin
  58702. else {
  58703. this._particle._stillInvisible = true; // mark the particle as invisible
  58704. for (pt = 0; pt < this._shape.length; pt++) {
  58705. idx = index + pt * 3;
  58706. colidx = colorIndex + pt * 4;
  58707. uvidx = uvIndex + pt * 2;
  58708. this._positions32[idx] = 0.0;
  58709. this._positions32[idx + 1] = 0.0;
  58710. this._positions32[idx + 2] = 0.0;
  58711. this._normals32[idx] = 0.0;
  58712. this._normals32[idx + 1] = 0.0;
  58713. this._normals32[idx + 2] = 0.0;
  58714. if (this._computeParticleColor && this._particle.color) {
  58715. this._colors32[colidx] = this._particle.color.r;
  58716. this._colors32[colidx + 1] = this._particle.color.g;
  58717. this._colors32[colidx + 2] = this._particle.color.b;
  58718. this._colors32[colidx + 3] = this._particle.color.a;
  58719. }
  58720. if (this._computeParticleTexture) {
  58721. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58722. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58723. }
  58724. }
  58725. }
  58726. // if the particle intersections must be computed : update the bbInfo
  58727. if (this._particlesIntersect) {
  58728. var bInfo = this._particle._boundingInfo;
  58729. var bBox = bInfo.boundingBox;
  58730. var bSphere = bInfo.boundingSphere;
  58731. if (!this._bSphereOnly) {
  58732. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58733. for (var b = 0; b < bBox.vectors.length; b++) {
  58734. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58735. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58736. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58737. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58738. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58739. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58740. 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;
  58741. 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;
  58742. 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;
  58743. }
  58744. bBox._update(this.mesh._worldMatrix);
  58745. }
  58746. // place and scale the particle bouding sphere in the SPS local system, then update it
  58747. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58748. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58749. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58750. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58751. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58752. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58753. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58754. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58755. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58756. 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));
  58757. bSphere._update(this.mesh._worldMatrix);
  58758. }
  58759. // increment indexes for the next particle
  58760. index = idx + 3;
  58761. colorIndex = colidx + 4;
  58762. uvIndex = uvidx + 2;
  58763. }
  58764. // if the VBO must be updated
  58765. if (update) {
  58766. if (this._computeParticleColor) {
  58767. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58768. }
  58769. if (this._computeParticleTexture) {
  58770. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58771. }
  58772. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58773. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58774. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58775. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58776. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58777. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58778. for (var i = 0; i < this._normals32.length; i++) {
  58779. this._fixedNormal32[i] = this._normals32[i];
  58780. }
  58781. }
  58782. if (!this.mesh.areNormalsFrozen) {
  58783. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58784. }
  58785. }
  58786. if (this._depthSort && this._depthSortParticles) {
  58787. this.depthSortedParticles.sort(this._depthSortFunction);
  58788. var dspl = this.depthSortedParticles.length;
  58789. var sorted = 0;
  58790. var lind = 0;
  58791. var sind = 0;
  58792. var sid = 0;
  58793. for (sorted = 0; sorted < dspl; sorted++) {
  58794. lind = this.depthSortedParticles[sorted].indicesLength;
  58795. sind = this.depthSortedParticles[sorted].ind;
  58796. for (var i = 0; i < lind; i++) {
  58797. this._indices32[sid] = this._indices[sind + i];
  58798. sid++;
  58799. }
  58800. }
  58801. this.mesh.updateIndices(this._indices32);
  58802. }
  58803. }
  58804. if (this._computeBoundingBox) {
  58805. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58806. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58807. }
  58808. this.afterUpdateParticles(start, end, update);
  58809. return this;
  58810. };
  58811. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58812. this._halfroll = this._roll * 0.5;
  58813. this._halfpitch = this._pitch * 0.5;
  58814. this._halfyaw = this._yaw * 0.5;
  58815. this._sinRoll = Math.sin(this._halfroll);
  58816. this._cosRoll = Math.cos(this._halfroll);
  58817. this._sinPitch = Math.sin(this._halfpitch);
  58818. this._cosPitch = Math.cos(this._halfpitch);
  58819. this._sinYaw = Math.sin(this._halfyaw);
  58820. this._cosYaw = Math.cos(this._halfyaw);
  58821. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58822. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58823. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58824. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58825. };
  58826. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58827. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58828. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58829. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58830. this._rotMatrix.m[3] = 0;
  58831. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58832. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58833. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58834. this._rotMatrix.m[7] = 0;
  58835. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58836. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58837. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58838. this._rotMatrix.m[11] = 0;
  58839. this._rotMatrix.m[12] = 0;
  58840. this._rotMatrix.m[13] = 0;
  58841. this._rotMatrix.m[14] = 0;
  58842. this._rotMatrix.m[15] = 1.0;
  58843. };
  58844. /**
  58845. * Disposes the SPS.
  58846. */
  58847. SolidParticleSystem.prototype.dispose = function () {
  58848. this.mesh.dispose();
  58849. this.vars = null;
  58850. // drop references to internal big arrays for the GC
  58851. this._positions = null;
  58852. this._indices = null;
  58853. this._normals = null;
  58854. this._uvs = null;
  58855. this._colors = null;
  58856. this._indices32 = null;
  58857. this._positions32 = null;
  58858. this._normals32 = null;
  58859. this._fixedNormal32 = null;
  58860. this._uvs32 = null;
  58861. this._colors32 = null;
  58862. this.pickedParticles = null;
  58863. };
  58864. /**
  58865. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58866. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58867. * @returns the SPS.
  58868. */
  58869. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58870. if (!this._isVisibilityBoxLocked) {
  58871. this.mesh.refreshBoundingInfo();
  58872. }
  58873. return this;
  58874. };
  58875. /**
  58876. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58877. * @param size the size (float) of the visibility box
  58878. * note : this doesn't lock the SPS mesh bounding box.
  58879. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58880. */
  58881. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58882. var vis = size / 2;
  58883. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58884. };
  58885. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58886. /**
  58887. * Gets whether the SPS as always visible or not
  58888. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58889. */
  58890. get: function () {
  58891. return this._alwaysVisible;
  58892. },
  58893. /**
  58894. * Sets the SPS as always visible or not
  58895. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58896. */
  58897. set: function (val) {
  58898. this._alwaysVisible = val;
  58899. this.mesh.alwaysSelectAsActiveMesh = val;
  58900. },
  58901. enumerable: true,
  58902. configurable: true
  58903. });
  58904. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58905. /**
  58906. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58907. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58908. */
  58909. get: function () {
  58910. return this._isVisibilityBoxLocked;
  58911. },
  58912. /**
  58913. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58914. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58915. */
  58916. set: function (val) {
  58917. this._isVisibilityBoxLocked = val;
  58918. var boundingInfo = this.mesh.getBoundingInfo();
  58919. boundingInfo.isLocked = val;
  58920. },
  58921. enumerable: true,
  58922. configurable: true
  58923. });
  58924. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58925. /**
  58926. * Gets if `setParticles()` computes the particle rotations or not.
  58927. * Default value : true. The SPS is faster when it's set to false.
  58928. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58929. */
  58930. get: function () {
  58931. return this._computeParticleRotation;
  58932. },
  58933. /**
  58934. * Tells to `setParticles()` to compute the particle rotations or not.
  58935. * Default value : true. The SPS is faster when it's set to false.
  58936. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58937. */
  58938. set: function (val) {
  58939. this._computeParticleRotation = val;
  58940. },
  58941. enumerable: true,
  58942. configurable: true
  58943. });
  58944. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  58945. /**
  58946. * Gets if `setParticles()` computes the particle colors or not.
  58947. * Default value : true. The SPS is faster when it's set to false.
  58948. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58949. */
  58950. get: function () {
  58951. return this._computeParticleColor;
  58952. },
  58953. /**
  58954. * Tells to `setParticles()` to compute the particle colors or not.
  58955. * Default value : true. The SPS is faster when it's set to false.
  58956. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58957. */
  58958. set: function (val) {
  58959. this._computeParticleColor = val;
  58960. },
  58961. enumerable: true,
  58962. configurable: true
  58963. });
  58964. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  58965. /**
  58966. * Gets if `setParticles()` computes the particle textures or not.
  58967. * Default value : true. The SPS is faster when it's set to false.
  58968. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  58969. */
  58970. get: function () {
  58971. return this._computeParticleTexture;
  58972. },
  58973. set: function (val) {
  58974. this._computeParticleTexture = val;
  58975. },
  58976. enumerable: true,
  58977. configurable: true
  58978. });
  58979. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  58980. /**
  58981. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  58982. * Default value : false. The SPS is faster when it's set to false.
  58983. * Note : the particle custom vertex positions aren't stored values.
  58984. */
  58985. get: function () {
  58986. return this._computeParticleVertex;
  58987. },
  58988. /**
  58989. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  58990. * Default value : false. The SPS is faster when it's set to false.
  58991. * Note : the particle custom vertex positions aren't stored values.
  58992. */
  58993. set: function (val) {
  58994. this._computeParticleVertex = val;
  58995. },
  58996. enumerable: true,
  58997. configurable: true
  58998. });
  58999. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59000. /**
  59001. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59002. */
  59003. get: function () {
  59004. return this._computeBoundingBox;
  59005. },
  59006. /**
  59007. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59008. */
  59009. set: function (val) {
  59010. this._computeBoundingBox = val;
  59011. },
  59012. enumerable: true,
  59013. configurable: true
  59014. });
  59015. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59016. /**
  59017. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59018. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59019. * Default : `true`
  59020. */
  59021. get: function () {
  59022. return this._depthSortParticles;
  59023. },
  59024. /**
  59025. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59026. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59027. * Default : `true`
  59028. */
  59029. set: function (val) {
  59030. this._depthSortParticles = val;
  59031. },
  59032. enumerable: true,
  59033. configurable: true
  59034. });
  59035. // =======================================================================
  59036. // Particle behavior logic
  59037. // these following methods may be overwritten by the user to fit his needs
  59038. /**
  59039. * This function does nothing. It may be overwritten to set all the particle first values.
  59040. * The SPS doesn't call this function, you may have to call it by your own.
  59041. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59042. */
  59043. SolidParticleSystem.prototype.initParticles = function () {
  59044. };
  59045. /**
  59046. * This function does nothing. It may be overwritten to recycle a particle.
  59047. * The SPS doesn't call this function, you may have to call it by your own.
  59048. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59049. * @param particle The particle to recycle
  59050. * @returns the recycled particle
  59051. */
  59052. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59053. return particle;
  59054. };
  59055. /**
  59056. * Updates a particle : this function should be overwritten by the user.
  59057. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59058. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59059. * @example : just set a particle position or velocity and recycle conditions
  59060. * @param particle The particle to update
  59061. * @returns the updated particle
  59062. */
  59063. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59064. return particle;
  59065. };
  59066. /**
  59067. * Updates a vertex of a particle : it can be overwritten by the user.
  59068. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59069. * @param particle the current particle
  59070. * @param vertex the current index of the current particle
  59071. * @param pt the index of the current vertex in the particle shape
  59072. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59073. * @example : just set a vertex particle position
  59074. * @returns the updated vertex
  59075. */
  59076. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59077. return vertex;
  59078. };
  59079. /**
  59080. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59081. * This does nothing and may be overwritten by the user.
  59082. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59083. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59084. * @param update the boolean update value actually passed to setParticles()
  59085. */
  59086. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59087. };
  59088. /**
  59089. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59090. * This will be passed three parameters.
  59091. * This does nothing and may be overwritten by the user.
  59092. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59093. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59094. * @param update the boolean update value actually passed to setParticles()
  59095. */
  59096. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59097. };
  59098. return SolidParticleSystem;
  59099. }());
  59100. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59101. })(BABYLON || (BABYLON = {}));
  59102. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59103. var BABYLON;
  59104. (function (BABYLON) {
  59105. var ShaderMaterial = /** @class */ (function (_super) {
  59106. __extends(ShaderMaterial, _super);
  59107. function ShaderMaterial(name, scene, shaderPath, options) {
  59108. var _this = _super.call(this, name, scene) || this;
  59109. _this._textures = {};
  59110. _this._textureArrays = {};
  59111. _this._floats = {};
  59112. _this._ints = {};
  59113. _this._floatsArrays = {};
  59114. _this._colors3 = {};
  59115. _this._colors3Arrays = {};
  59116. _this._colors4 = {};
  59117. _this._vectors2 = {};
  59118. _this._vectors3 = {};
  59119. _this._vectors4 = {};
  59120. _this._matrices = {};
  59121. _this._matrices3x3 = {};
  59122. _this._matrices2x2 = {};
  59123. _this._vectors2Arrays = {};
  59124. _this._vectors3Arrays = {};
  59125. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59126. _this._shaderPath = shaderPath;
  59127. options.needAlphaBlending = options.needAlphaBlending || false;
  59128. options.needAlphaTesting = options.needAlphaTesting || false;
  59129. options.attributes = options.attributes || ["position", "normal", "uv"];
  59130. options.uniforms = options.uniforms || ["worldViewProjection"];
  59131. options.uniformBuffers = options.uniformBuffers || [];
  59132. options.samplers = options.samplers || [];
  59133. options.defines = options.defines || [];
  59134. _this._options = options;
  59135. return _this;
  59136. }
  59137. ShaderMaterial.prototype.getClassName = function () {
  59138. return "ShaderMaterial";
  59139. };
  59140. ShaderMaterial.prototype.needAlphaBlending = function () {
  59141. return this._options.needAlphaBlending;
  59142. };
  59143. ShaderMaterial.prototype.needAlphaTesting = function () {
  59144. return this._options.needAlphaTesting;
  59145. };
  59146. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59147. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59148. this._options.uniforms.push(uniformName);
  59149. }
  59150. };
  59151. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59152. if (this._options.samplers.indexOf(name) === -1) {
  59153. this._options.samplers.push(name);
  59154. }
  59155. this._textures[name] = texture;
  59156. return this;
  59157. };
  59158. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59159. if (this._options.samplers.indexOf(name) === -1) {
  59160. this._options.samplers.push(name);
  59161. }
  59162. this._checkUniform(name);
  59163. this._textureArrays[name] = textures;
  59164. return this;
  59165. };
  59166. ShaderMaterial.prototype.setFloat = function (name, value) {
  59167. this._checkUniform(name);
  59168. this._floats[name] = value;
  59169. return this;
  59170. };
  59171. ShaderMaterial.prototype.setInt = function (name, value) {
  59172. this._checkUniform(name);
  59173. this._ints[name] = value;
  59174. return this;
  59175. };
  59176. ShaderMaterial.prototype.setFloats = function (name, value) {
  59177. this._checkUniform(name);
  59178. this._floatsArrays[name] = value;
  59179. return this;
  59180. };
  59181. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59182. this._checkUniform(name);
  59183. this._colors3[name] = value;
  59184. return this;
  59185. };
  59186. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59187. this._checkUniform(name);
  59188. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59189. color.toArray(arr, arr.length);
  59190. return arr;
  59191. }, []);
  59192. return this;
  59193. };
  59194. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59195. this._checkUniform(name);
  59196. this._colors4[name] = value;
  59197. return this;
  59198. };
  59199. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59200. this._checkUniform(name);
  59201. this._vectors2[name] = value;
  59202. return this;
  59203. };
  59204. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59205. this._checkUniform(name);
  59206. this._vectors3[name] = value;
  59207. return this;
  59208. };
  59209. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59210. this._checkUniform(name);
  59211. this._vectors4[name] = value;
  59212. return this;
  59213. };
  59214. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59215. this._checkUniform(name);
  59216. this._matrices[name] = value;
  59217. return this;
  59218. };
  59219. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59220. this._checkUniform(name);
  59221. this._matrices3x3[name] = value;
  59222. return this;
  59223. };
  59224. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59225. this._checkUniform(name);
  59226. this._matrices2x2[name] = value;
  59227. return this;
  59228. };
  59229. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59230. this._checkUniform(name);
  59231. this._vectors2Arrays[name] = value;
  59232. return this;
  59233. };
  59234. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59235. this._checkUniform(name);
  59236. this._vectors3Arrays[name] = value;
  59237. return this;
  59238. };
  59239. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59240. if (!mesh) {
  59241. return true;
  59242. }
  59243. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59244. return false;
  59245. }
  59246. return false;
  59247. };
  59248. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59249. var scene = this.getScene();
  59250. var engine = scene.getEngine();
  59251. if (!this.checkReadyOnEveryCall) {
  59252. if (this._renderId === scene.getRenderId()) {
  59253. if (this._checkCache(scene, mesh, useInstances)) {
  59254. return true;
  59255. }
  59256. }
  59257. }
  59258. // Instances
  59259. var defines = [];
  59260. var attribs = [];
  59261. var fallbacks = new BABYLON.EffectFallbacks();
  59262. if (useInstances) {
  59263. defines.push("#define INSTANCES");
  59264. }
  59265. for (var index = 0; index < this._options.defines.length; index++) {
  59266. defines.push(this._options.defines[index]);
  59267. }
  59268. for (var index = 0; index < this._options.attributes.length; index++) {
  59269. attribs.push(this._options.attributes[index]);
  59270. }
  59271. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59272. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59273. defines.push("#define VERTEXCOLOR");
  59274. }
  59275. // Bones
  59276. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59277. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59278. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59279. if (mesh.numBoneInfluencers > 4) {
  59280. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59281. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59282. }
  59283. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59284. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59285. fallbacks.addCPUSkinningFallback(0, mesh);
  59286. if (this._options.uniforms.indexOf("mBones") === -1) {
  59287. this._options.uniforms.push("mBones");
  59288. }
  59289. }
  59290. else {
  59291. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59292. }
  59293. // Textures
  59294. for (var name in this._textures) {
  59295. if (!this._textures[name].isReady()) {
  59296. return false;
  59297. }
  59298. }
  59299. // Alpha test
  59300. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59301. defines.push("#define ALPHATEST");
  59302. }
  59303. var previousEffect = this._effect;
  59304. var join = defines.join("\n");
  59305. this._effect = engine.createEffect(this._shaderPath, {
  59306. attributes: attribs,
  59307. uniformsNames: this._options.uniforms,
  59308. uniformBuffersNames: this._options.uniformBuffers,
  59309. samplers: this._options.samplers,
  59310. defines: join,
  59311. fallbacks: fallbacks,
  59312. onCompiled: this.onCompiled,
  59313. onError: this.onError
  59314. }, engine);
  59315. if (!this._effect.isReady()) {
  59316. return false;
  59317. }
  59318. if (previousEffect !== this._effect) {
  59319. scene.resetCachedMaterial();
  59320. }
  59321. this._renderId = scene.getRenderId();
  59322. return true;
  59323. };
  59324. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59325. var scene = this.getScene();
  59326. if (!this._effect) {
  59327. return;
  59328. }
  59329. if (this._options.uniforms.indexOf("world") !== -1) {
  59330. this._effect.setMatrix("world", world);
  59331. }
  59332. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59333. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59334. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59335. }
  59336. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59337. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59338. }
  59339. };
  59340. ShaderMaterial.prototype.bind = function (world, mesh) {
  59341. // Std values
  59342. this.bindOnlyWorldMatrix(world);
  59343. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59344. if (this._options.uniforms.indexOf("view") !== -1) {
  59345. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59346. }
  59347. if (this._options.uniforms.indexOf("projection") !== -1) {
  59348. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59349. }
  59350. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59351. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59352. }
  59353. // Bones
  59354. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59355. var name;
  59356. // Texture
  59357. for (name in this._textures) {
  59358. this._effect.setTexture(name, this._textures[name]);
  59359. }
  59360. // Texture arrays
  59361. for (name in this._textureArrays) {
  59362. this._effect.setTextureArray(name, this._textureArrays[name]);
  59363. }
  59364. // Int
  59365. for (name in this._ints) {
  59366. this._effect.setInt(name, this._ints[name]);
  59367. }
  59368. // Float
  59369. for (name in this._floats) {
  59370. this._effect.setFloat(name, this._floats[name]);
  59371. }
  59372. // Floats
  59373. for (name in this._floatsArrays) {
  59374. this._effect.setArray(name, this._floatsArrays[name]);
  59375. }
  59376. // Color3
  59377. for (name in this._colors3) {
  59378. this._effect.setColor3(name, this._colors3[name]);
  59379. }
  59380. for (name in this._colors3Arrays) {
  59381. this._effect.setArray3(name, this._colors3Arrays[name]);
  59382. }
  59383. // Color4
  59384. for (name in this._colors4) {
  59385. var color = this._colors4[name];
  59386. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59387. }
  59388. // Vector2
  59389. for (name in this._vectors2) {
  59390. this._effect.setVector2(name, this._vectors2[name]);
  59391. }
  59392. // Vector3
  59393. for (name in this._vectors3) {
  59394. this._effect.setVector3(name, this._vectors3[name]);
  59395. }
  59396. // Vector4
  59397. for (name in this._vectors4) {
  59398. this._effect.setVector4(name, this._vectors4[name]);
  59399. }
  59400. // Matrix
  59401. for (name in this._matrices) {
  59402. this._effect.setMatrix(name, this._matrices[name]);
  59403. }
  59404. // Matrix 3x3
  59405. for (name in this._matrices3x3) {
  59406. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59407. }
  59408. // Matrix 2x2
  59409. for (name in this._matrices2x2) {
  59410. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59411. }
  59412. // Vector2Array
  59413. for (name in this._vectors2Arrays) {
  59414. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59415. }
  59416. // Vector3Array
  59417. for (name in this._vectors3Arrays) {
  59418. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59419. }
  59420. }
  59421. this._afterBind(mesh);
  59422. };
  59423. ShaderMaterial.prototype.getActiveTextures = function () {
  59424. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59425. for (var name in this._textures) {
  59426. activeTextures.push(this._textures[name]);
  59427. }
  59428. for (var name in this._textureArrays) {
  59429. var array = this._textureArrays[name];
  59430. for (var index = 0; index < array.length; index++) {
  59431. activeTextures.push(array[index]);
  59432. }
  59433. }
  59434. return activeTextures;
  59435. };
  59436. ShaderMaterial.prototype.hasTexture = function (texture) {
  59437. if (_super.prototype.hasTexture.call(this, texture)) {
  59438. return true;
  59439. }
  59440. for (var name in this._textures) {
  59441. if (this._textures[name] === texture) {
  59442. return true;
  59443. }
  59444. }
  59445. for (var name in this._textureArrays) {
  59446. var array = this._textureArrays[name];
  59447. for (var index = 0; index < array.length; index++) {
  59448. if (array[index] === texture) {
  59449. return true;
  59450. }
  59451. }
  59452. }
  59453. return false;
  59454. };
  59455. ShaderMaterial.prototype.clone = function (name) {
  59456. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59457. return newShaderMaterial;
  59458. };
  59459. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59460. if (forceDisposeTextures) {
  59461. var name;
  59462. for (name in this._textures) {
  59463. this._textures[name].dispose();
  59464. }
  59465. for (name in this._textureArrays) {
  59466. var array = this._textureArrays[name];
  59467. for (var index = 0; index < array.length; index++) {
  59468. array[index].dispose();
  59469. }
  59470. }
  59471. }
  59472. this._textures = {};
  59473. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59474. };
  59475. ShaderMaterial.prototype.serialize = function () {
  59476. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59477. serializationObject.customType = "BABYLON.ShaderMaterial";
  59478. serializationObject.options = this._options;
  59479. serializationObject.shaderPath = this._shaderPath;
  59480. var name;
  59481. // Texture
  59482. serializationObject.textures = {};
  59483. for (name in this._textures) {
  59484. serializationObject.textures[name] = this._textures[name].serialize();
  59485. }
  59486. // Texture arrays
  59487. serializationObject.textureArrays = {};
  59488. for (name in this._textureArrays) {
  59489. serializationObject.textureArrays[name] = [];
  59490. var array = this._textureArrays[name];
  59491. for (var index = 0; index < array.length; index++) {
  59492. serializationObject.textureArrays[name].push(array[index].serialize());
  59493. }
  59494. }
  59495. // Float
  59496. serializationObject.floats = {};
  59497. for (name in this._floats) {
  59498. serializationObject.floats[name] = this._floats[name];
  59499. }
  59500. // Float s
  59501. serializationObject.FloatArrays = {};
  59502. for (name in this._floatsArrays) {
  59503. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59504. }
  59505. // Color3
  59506. serializationObject.colors3 = {};
  59507. for (name in this._colors3) {
  59508. serializationObject.colors3[name] = this._colors3[name].asArray();
  59509. }
  59510. // Color3 array
  59511. serializationObject.colors3Arrays = {};
  59512. for (name in this._colors3Arrays) {
  59513. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59514. }
  59515. // Color4
  59516. serializationObject.colors4 = {};
  59517. for (name in this._colors4) {
  59518. serializationObject.colors4[name] = this._colors4[name].asArray();
  59519. }
  59520. // Vector2
  59521. serializationObject.vectors2 = {};
  59522. for (name in this._vectors2) {
  59523. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59524. }
  59525. // Vector3
  59526. serializationObject.vectors3 = {};
  59527. for (name in this._vectors3) {
  59528. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59529. }
  59530. // Vector4
  59531. serializationObject.vectors4 = {};
  59532. for (name in this._vectors4) {
  59533. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59534. }
  59535. // Matrix
  59536. serializationObject.matrices = {};
  59537. for (name in this._matrices) {
  59538. serializationObject.matrices[name] = this._matrices[name].asArray();
  59539. }
  59540. // Matrix 3x3
  59541. serializationObject.matrices3x3 = {};
  59542. for (name in this._matrices3x3) {
  59543. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59544. }
  59545. // Matrix 2x2
  59546. serializationObject.matrices2x2 = {};
  59547. for (name in this._matrices2x2) {
  59548. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59549. }
  59550. // Vector2Array
  59551. serializationObject.vectors2Arrays = {};
  59552. for (name in this._vectors2Arrays) {
  59553. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59554. }
  59555. // Vector3Array
  59556. serializationObject.vectors3Arrays = {};
  59557. for (name in this._vectors3Arrays) {
  59558. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59559. }
  59560. return serializationObject;
  59561. };
  59562. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59563. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59564. var name;
  59565. // Texture
  59566. for (name in source.textures) {
  59567. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59568. }
  59569. // Texture arrays
  59570. for (name in source.textureArrays) {
  59571. var array = source.textureArrays[name];
  59572. var textureArray = new Array();
  59573. for (var index = 0; index < array.length; index++) {
  59574. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59575. }
  59576. material.setTextureArray(name, textureArray);
  59577. }
  59578. // Float
  59579. for (name in source.floats) {
  59580. material.setFloat(name, source.floats[name]);
  59581. }
  59582. // Float s
  59583. for (name in source.floatsArrays) {
  59584. material.setFloats(name, source.floatsArrays[name]);
  59585. }
  59586. // Color3
  59587. for (name in source.colors3) {
  59588. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59589. }
  59590. // Color3 arrays
  59591. for (name in source.colors3Arrays) {
  59592. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59593. if (i % 3 === 0) {
  59594. arr.push([num]);
  59595. }
  59596. else {
  59597. arr[arr.length - 1].push(num);
  59598. }
  59599. return arr;
  59600. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59601. material.setColor3Array(name, colors);
  59602. }
  59603. // Color4
  59604. for (name in source.colors4) {
  59605. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59606. }
  59607. // Vector2
  59608. for (name in source.vectors2) {
  59609. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59610. }
  59611. // Vector3
  59612. for (name in source.vectors3) {
  59613. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59614. }
  59615. // Vector4
  59616. for (name in source.vectors4) {
  59617. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59618. }
  59619. // Matrix
  59620. for (name in source.matrices) {
  59621. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59622. }
  59623. // Matrix 3x3
  59624. for (name in source.matrices3x3) {
  59625. material.setMatrix3x3(name, source.matrices3x3[name]);
  59626. }
  59627. // Matrix 2x2
  59628. for (name in source.matrices2x2) {
  59629. material.setMatrix2x2(name, source.matrices2x2[name]);
  59630. }
  59631. // Vector2Array
  59632. for (name in source.vectors2Arrays) {
  59633. material.setArray2(name, source.vectors2Arrays[name]);
  59634. }
  59635. // Vector3Array
  59636. for (name in source.vectors3Arrays) {
  59637. material.setArray3(name, source.vectors3Arrays[name]);
  59638. }
  59639. return material;
  59640. };
  59641. return ShaderMaterial;
  59642. }(BABYLON.Material));
  59643. BABYLON.ShaderMaterial = ShaderMaterial;
  59644. })(BABYLON || (BABYLON = {}));
  59645. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59646. var BABYLON;
  59647. (function (BABYLON) {
  59648. var GroundMesh = /** @class */ (function (_super) {
  59649. __extends(GroundMesh, _super);
  59650. function GroundMesh(name, scene) {
  59651. var _this = _super.call(this, name, scene) || this;
  59652. _this.generateOctree = false;
  59653. return _this;
  59654. }
  59655. GroundMesh.prototype.getClassName = function () {
  59656. return "GroundMesh";
  59657. };
  59658. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59659. get: function () {
  59660. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59661. },
  59662. enumerable: true,
  59663. configurable: true
  59664. });
  59665. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59666. get: function () {
  59667. return this._subdivisionsX;
  59668. },
  59669. enumerable: true,
  59670. configurable: true
  59671. });
  59672. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59673. get: function () {
  59674. return this._subdivisionsY;
  59675. },
  59676. enumerable: true,
  59677. configurable: true
  59678. });
  59679. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59680. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59681. this._subdivisionsX = chunksCount;
  59682. this._subdivisionsY = chunksCount;
  59683. this.subdivide(chunksCount);
  59684. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59685. };
  59686. /**
  59687. * Returns a height (y) value in the Worl system :
  59688. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59689. * Returns the ground y position if (x, z) are outside the ground surface.
  59690. */
  59691. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59692. var world = this.getWorldMatrix();
  59693. var invMat = BABYLON.Tmp.Matrix[5];
  59694. world.invertToRef(invMat);
  59695. var tmpVect = BABYLON.Tmp.Vector3[8];
  59696. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59697. x = tmpVect.x;
  59698. z = tmpVect.z;
  59699. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59700. return this.position.y;
  59701. }
  59702. if (!this._heightQuads || this._heightQuads.length == 0) {
  59703. this._initHeightQuads();
  59704. this._computeHeightQuads();
  59705. }
  59706. var facet = this._getFacetAt(x, z);
  59707. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59708. // return y in the World system
  59709. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59710. return tmpVect.y;
  59711. };
  59712. /**
  59713. * Returns a normalized vector (Vector3) orthogonal to the ground
  59714. * at the ground coordinates (x, z) expressed in the World system.
  59715. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59716. */
  59717. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59718. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59719. this.getNormalAtCoordinatesToRef(x, z, normal);
  59720. return normal;
  59721. };
  59722. /**
  59723. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59724. * at the ground coordinates (x, z) expressed in the World system.
  59725. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59726. * Returns the GroundMesh.
  59727. */
  59728. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59729. var world = this.getWorldMatrix();
  59730. var tmpMat = BABYLON.Tmp.Matrix[5];
  59731. world.invertToRef(tmpMat);
  59732. var tmpVect = BABYLON.Tmp.Vector3[8];
  59733. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59734. x = tmpVect.x;
  59735. z = tmpVect.z;
  59736. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59737. return this;
  59738. }
  59739. if (!this._heightQuads || this._heightQuads.length == 0) {
  59740. this._initHeightQuads();
  59741. this._computeHeightQuads();
  59742. }
  59743. var facet = this._getFacetAt(x, z);
  59744. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59745. return this;
  59746. };
  59747. /**
  59748. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59749. * if the ground has been updated.
  59750. * This can be used in the render loop.
  59751. * Returns the GroundMesh.
  59752. */
  59753. GroundMesh.prototype.updateCoordinateHeights = function () {
  59754. if (!this._heightQuads || this._heightQuads.length == 0) {
  59755. this._initHeightQuads();
  59756. }
  59757. this._computeHeightQuads();
  59758. return this;
  59759. };
  59760. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59761. GroundMesh.prototype._getFacetAt = function (x, z) {
  59762. // retrieve col and row from x, z coordinates in the ground local system
  59763. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59764. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59765. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59766. var facet;
  59767. if (z < quad.slope.x * x + quad.slope.y) {
  59768. facet = quad.facet1;
  59769. }
  59770. else {
  59771. facet = quad.facet2;
  59772. }
  59773. return facet;
  59774. };
  59775. // Creates and populates the heightMap array with "facet" elements :
  59776. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59777. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59778. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59779. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59780. // Returns the GroundMesh.
  59781. GroundMesh.prototype._initHeightQuads = function () {
  59782. var subdivisionsX = this._subdivisionsX;
  59783. var subdivisionsY = this._subdivisionsY;
  59784. this._heightQuads = new Array();
  59785. for (var row = 0; row < subdivisionsY; row++) {
  59786. for (var col = 0; col < subdivisionsX; col++) {
  59787. 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) };
  59788. this._heightQuads[row * subdivisionsX + col] = quad;
  59789. }
  59790. }
  59791. return this;
  59792. };
  59793. // Compute each quad element values and update the the heightMap array :
  59794. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59795. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59796. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59797. // Returns the GroundMesh.
  59798. GroundMesh.prototype._computeHeightQuads = function () {
  59799. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59800. if (!positions) {
  59801. return this;
  59802. }
  59803. var v1 = BABYLON.Tmp.Vector3[3];
  59804. var v2 = BABYLON.Tmp.Vector3[2];
  59805. var v3 = BABYLON.Tmp.Vector3[1];
  59806. var v4 = BABYLON.Tmp.Vector3[0];
  59807. var v1v2 = BABYLON.Tmp.Vector3[4];
  59808. var v1v3 = BABYLON.Tmp.Vector3[5];
  59809. var v1v4 = BABYLON.Tmp.Vector3[6];
  59810. var norm1 = BABYLON.Tmp.Vector3[7];
  59811. var norm2 = BABYLON.Tmp.Vector3[8];
  59812. var i = 0;
  59813. var j = 0;
  59814. var k = 0;
  59815. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59816. var h = 0;
  59817. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59818. var d2 = 0;
  59819. var subdivisionsX = this._subdivisionsX;
  59820. var subdivisionsY = this._subdivisionsY;
  59821. for (var row = 0; row < subdivisionsY; row++) {
  59822. for (var col = 0; col < subdivisionsX; col++) {
  59823. i = col * 3;
  59824. j = row * (subdivisionsX + 1) * 3;
  59825. k = (row + 1) * (subdivisionsX + 1) * 3;
  59826. v1.x = positions[j + i];
  59827. v1.y = positions[j + i + 1];
  59828. v1.z = positions[j + i + 2];
  59829. v2.x = positions[j + i + 3];
  59830. v2.y = positions[j + i + 4];
  59831. v2.z = positions[j + i + 5];
  59832. v3.x = positions[k + i];
  59833. v3.y = positions[k + i + 1];
  59834. v3.z = positions[k + i + 2];
  59835. v4.x = positions[k + i + 3];
  59836. v4.y = positions[k + i + 4];
  59837. v4.z = positions[k + i + 5];
  59838. // 2D slope V1V4
  59839. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59840. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59841. // facet equations :
  59842. // we compute each facet normal vector
  59843. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59844. // we compute the value d by applying the equation to v1 which belongs to the plane
  59845. // then we store the facet equation in a Vector4
  59846. v2.subtractToRef(v1, v1v2);
  59847. v3.subtractToRef(v1, v1v3);
  59848. v4.subtractToRef(v1, v1v4);
  59849. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59850. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59851. norm1.normalize();
  59852. norm2.normalize();
  59853. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59854. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59855. var quad = this._heightQuads[row * subdivisionsX + col];
  59856. quad.slope.copyFromFloats(cd, h);
  59857. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59858. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59859. }
  59860. }
  59861. return this;
  59862. };
  59863. GroundMesh.prototype.serialize = function (serializationObject) {
  59864. _super.prototype.serialize.call(this, serializationObject);
  59865. serializationObject.subdivisionsX = this._subdivisionsX;
  59866. serializationObject.subdivisionsY = this._subdivisionsY;
  59867. serializationObject.minX = this._minX;
  59868. serializationObject.maxX = this._maxX;
  59869. serializationObject.minZ = this._minZ;
  59870. serializationObject.maxZ = this._maxZ;
  59871. serializationObject.width = this._width;
  59872. serializationObject.height = this._height;
  59873. };
  59874. GroundMesh.Parse = function (parsedMesh, scene) {
  59875. var result = new GroundMesh(parsedMesh.name, scene);
  59876. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59877. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59878. result._minX = parsedMesh.minX;
  59879. result._maxX = parsedMesh.maxX;
  59880. result._minZ = parsedMesh.minZ;
  59881. result._maxZ = parsedMesh.maxZ;
  59882. result._width = parsedMesh.width;
  59883. result._height = parsedMesh.height;
  59884. return result;
  59885. };
  59886. return GroundMesh;
  59887. }(BABYLON.Mesh));
  59888. BABYLON.GroundMesh = GroundMesh;
  59889. })(BABYLON || (BABYLON = {}));
  59890. //# sourceMappingURL=babylon.groundMesh.js.map
  59891. var BABYLON;
  59892. (function (BABYLON) {
  59893. /**
  59894. * Creates an instance based on a source mesh.
  59895. */
  59896. var InstancedMesh = /** @class */ (function (_super) {
  59897. __extends(InstancedMesh, _super);
  59898. function InstancedMesh(name, source) {
  59899. var _this = _super.call(this, name, source.getScene()) || this;
  59900. source.instances.push(_this);
  59901. _this._sourceMesh = source;
  59902. _this.position.copyFrom(source.position);
  59903. _this.rotation.copyFrom(source.rotation);
  59904. _this.scaling.copyFrom(source.scaling);
  59905. if (source.rotationQuaternion) {
  59906. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59907. }
  59908. _this.infiniteDistance = source.infiniteDistance;
  59909. _this.setPivotMatrix(source.getPivotMatrix());
  59910. _this.refreshBoundingInfo();
  59911. _this._syncSubMeshes();
  59912. return _this;
  59913. }
  59914. /**
  59915. * Returns the string "InstancedMesh".
  59916. */
  59917. InstancedMesh.prototype.getClassName = function () {
  59918. return "InstancedMesh";
  59919. };
  59920. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59921. // Methods
  59922. get: function () {
  59923. return this._sourceMesh.receiveShadows;
  59924. },
  59925. enumerable: true,
  59926. configurable: true
  59927. });
  59928. Object.defineProperty(InstancedMesh.prototype, "material", {
  59929. get: function () {
  59930. return this._sourceMesh.material;
  59931. },
  59932. enumerable: true,
  59933. configurable: true
  59934. });
  59935. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59936. get: function () {
  59937. return this._sourceMesh.visibility;
  59938. },
  59939. enumerable: true,
  59940. configurable: true
  59941. });
  59942. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59943. get: function () {
  59944. return this._sourceMesh.skeleton;
  59945. },
  59946. enumerable: true,
  59947. configurable: true
  59948. });
  59949. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59950. get: function () {
  59951. return this._sourceMesh.renderingGroupId;
  59952. },
  59953. set: function (value) {
  59954. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59955. return;
  59956. }
  59957. //no-op with warning
  59958. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59959. },
  59960. enumerable: true,
  59961. configurable: true
  59962. });
  59963. /**
  59964. * Returns the total number of vertices (integer).
  59965. */
  59966. InstancedMesh.prototype.getTotalVertices = function () {
  59967. return this._sourceMesh.getTotalVertices();
  59968. };
  59969. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59970. get: function () {
  59971. return this._sourceMesh;
  59972. },
  59973. enumerable: true,
  59974. configurable: true
  59975. });
  59976. /**
  59977. * Is this node ready to be used/rendered
  59978. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59979. * @return {boolean} is it ready
  59980. */
  59981. InstancedMesh.prototype.isReady = function (completeCheck) {
  59982. if (completeCheck === void 0) { completeCheck = false; }
  59983. return this._sourceMesh.isReady(completeCheck, true);
  59984. };
  59985. /**
  59986. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59987. */
  59988. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59989. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59990. };
  59991. /**
  59992. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59993. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59994. * The `data` are either a numeric array either a Float32Array.
  59995. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59996. * 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).
  59997. * Note that a new underlying VertexBuffer object is created each call.
  59998. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59999. *
  60000. * Possible `kind` values :
  60001. * - BABYLON.VertexBuffer.PositionKind
  60002. * - BABYLON.VertexBuffer.UVKind
  60003. * - BABYLON.VertexBuffer.UV2Kind
  60004. * - BABYLON.VertexBuffer.UV3Kind
  60005. * - BABYLON.VertexBuffer.UV4Kind
  60006. * - BABYLON.VertexBuffer.UV5Kind
  60007. * - BABYLON.VertexBuffer.UV6Kind
  60008. * - BABYLON.VertexBuffer.ColorKind
  60009. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60010. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60011. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60012. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60013. *
  60014. * Returns the Mesh.
  60015. */
  60016. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60017. if (this.sourceMesh) {
  60018. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60019. }
  60020. return this.sourceMesh;
  60021. };
  60022. /**
  60023. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60024. * If the mesh has no geometry, it is simply returned as it is.
  60025. * The `data` are either a numeric array either a Float32Array.
  60026. * No new underlying VertexBuffer object is created.
  60027. * 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.
  60028. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60029. *
  60030. * Possible `kind` values :
  60031. * - BABYLON.VertexBuffer.PositionKind
  60032. * - BABYLON.VertexBuffer.UVKind
  60033. * - BABYLON.VertexBuffer.UV2Kind
  60034. * - BABYLON.VertexBuffer.UV3Kind
  60035. * - BABYLON.VertexBuffer.UV4Kind
  60036. * - BABYLON.VertexBuffer.UV5Kind
  60037. * - BABYLON.VertexBuffer.UV6Kind
  60038. * - BABYLON.VertexBuffer.ColorKind
  60039. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60040. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60041. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60042. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60043. *
  60044. * Returns the Mesh.
  60045. */
  60046. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60047. if (this.sourceMesh) {
  60048. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60049. }
  60050. return this.sourceMesh;
  60051. };
  60052. /**
  60053. * Sets the mesh indices.
  60054. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60055. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60056. * This method creates a new index buffer each call.
  60057. * Returns the Mesh.
  60058. */
  60059. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60060. if (totalVertices === void 0) { totalVertices = null; }
  60061. if (this.sourceMesh) {
  60062. this.sourceMesh.setIndices(indices, totalVertices);
  60063. }
  60064. return this.sourceMesh;
  60065. };
  60066. /**
  60067. * Boolean : True if the mesh owns the requested kind of data.
  60068. */
  60069. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60070. return this._sourceMesh.isVerticesDataPresent(kind);
  60071. };
  60072. /**
  60073. * Returns an array of indices (IndicesArray).
  60074. */
  60075. InstancedMesh.prototype.getIndices = function () {
  60076. return this._sourceMesh.getIndices();
  60077. };
  60078. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60079. get: function () {
  60080. return this._sourceMesh._positions;
  60081. },
  60082. enumerable: true,
  60083. configurable: true
  60084. });
  60085. /**
  60086. * Sets a new updated BoundingInfo to the mesh.
  60087. * Returns the mesh.
  60088. */
  60089. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60090. var meshBB = this._sourceMesh.getBoundingInfo();
  60091. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60092. this._updateBoundingInfo();
  60093. return this;
  60094. };
  60095. InstancedMesh.prototype._preActivate = function () {
  60096. if (this._currentLOD) {
  60097. this._currentLOD._preActivate();
  60098. }
  60099. return this;
  60100. };
  60101. InstancedMesh.prototype._activate = function (renderId) {
  60102. if (this._currentLOD) {
  60103. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60104. }
  60105. return this;
  60106. };
  60107. /**
  60108. * Returns the current associated LOD AbstractMesh.
  60109. */
  60110. InstancedMesh.prototype.getLOD = function (camera) {
  60111. if (!camera) {
  60112. return this;
  60113. }
  60114. var boundingInfo = this.getBoundingInfo();
  60115. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60116. if (this._currentLOD === this.sourceMesh) {
  60117. return this;
  60118. }
  60119. return this._currentLOD;
  60120. };
  60121. InstancedMesh.prototype._syncSubMeshes = function () {
  60122. this.releaseSubMeshes();
  60123. if (this._sourceMesh.subMeshes) {
  60124. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60125. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60126. }
  60127. }
  60128. return this;
  60129. };
  60130. InstancedMesh.prototype._generatePointsArray = function () {
  60131. return this._sourceMesh._generatePointsArray();
  60132. };
  60133. /**
  60134. * Creates a new InstancedMesh from the current mesh.
  60135. * - name (string) : the cloned mesh name
  60136. * - newParent (optional Node) : the optional Node to parent the clone to.
  60137. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60138. *
  60139. * Returns the clone.
  60140. */
  60141. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60142. var result = this._sourceMesh.createInstance(name);
  60143. // Deep copy
  60144. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60145. // Bounding info
  60146. this.refreshBoundingInfo();
  60147. // Parent
  60148. if (newParent) {
  60149. result.parent = newParent;
  60150. }
  60151. if (!doNotCloneChildren) {
  60152. // Children
  60153. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60154. var mesh = this.getScene().meshes[index];
  60155. if (mesh.parent === this) {
  60156. mesh.clone(mesh.name, result);
  60157. }
  60158. }
  60159. }
  60160. result.computeWorldMatrix(true);
  60161. return result;
  60162. };
  60163. /**
  60164. * Disposes the InstancedMesh.
  60165. * Returns nothing.
  60166. */
  60167. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60168. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60169. // Remove from mesh
  60170. var index = this._sourceMesh.instances.indexOf(this);
  60171. this._sourceMesh.instances.splice(index, 1);
  60172. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60173. };
  60174. return InstancedMesh;
  60175. }(BABYLON.AbstractMesh));
  60176. BABYLON.InstancedMesh = InstancedMesh;
  60177. })(BABYLON || (BABYLON = {}));
  60178. //# sourceMappingURL=babylon.instancedMesh.js.map
  60179. var BABYLON;
  60180. (function (BABYLON) {
  60181. var LinesMesh = /** @class */ (function (_super) {
  60182. __extends(LinesMesh, _super);
  60183. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60184. if (scene === void 0) { scene = null; }
  60185. if (parent === void 0) { parent = null; }
  60186. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60187. _this.useVertexColor = useVertexColor;
  60188. _this.useVertexAlpha = useVertexAlpha;
  60189. _this.color = new BABYLON.Color3(1, 1, 1);
  60190. _this.alpha = 1;
  60191. if (source) {
  60192. _this.color = source.color.clone();
  60193. _this.alpha = source.alpha;
  60194. _this.useVertexColor = source.useVertexColor;
  60195. _this.useVertexAlpha = source.useVertexAlpha;
  60196. }
  60197. _this._intersectionThreshold = 0.1;
  60198. var defines = [];
  60199. var options = {
  60200. attributes: [BABYLON.VertexBuffer.PositionKind],
  60201. uniforms: ["world", "viewProjection"],
  60202. needAlphaBlending: true,
  60203. defines: defines
  60204. };
  60205. if (useVertexAlpha === false) {
  60206. options.needAlphaBlending = false;
  60207. }
  60208. if (!useVertexColor) {
  60209. options.uniforms.push("color");
  60210. }
  60211. else {
  60212. options.defines.push("#define VERTEXCOLOR");
  60213. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60214. }
  60215. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60216. return _this;
  60217. }
  60218. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60219. /**
  60220. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60221. * This margin is expressed in world space coordinates, so its value may vary.
  60222. * Default value is 0.1
  60223. * @returns the intersection Threshold value.
  60224. */
  60225. get: function () {
  60226. return this._intersectionThreshold;
  60227. },
  60228. /**
  60229. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60230. * This margin is expressed in world space coordinates, so its value may vary.
  60231. * @param value the new threshold to apply
  60232. */
  60233. set: function (value) {
  60234. if (this._intersectionThreshold === value) {
  60235. return;
  60236. }
  60237. this._intersectionThreshold = value;
  60238. if (this.geometry) {
  60239. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60240. }
  60241. },
  60242. enumerable: true,
  60243. configurable: true
  60244. });
  60245. /**
  60246. * Returns the string "LineMesh"
  60247. */
  60248. LinesMesh.prototype.getClassName = function () {
  60249. return "LinesMesh";
  60250. };
  60251. Object.defineProperty(LinesMesh.prototype, "material", {
  60252. get: function () {
  60253. return this._colorShader;
  60254. },
  60255. set: function (value) {
  60256. // Do nothing
  60257. },
  60258. enumerable: true,
  60259. configurable: true
  60260. });
  60261. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60262. get: function () {
  60263. return false;
  60264. },
  60265. enumerable: true,
  60266. configurable: true
  60267. });
  60268. LinesMesh.prototype.createInstance = function (name) {
  60269. throw new Error("LinesMeshes do not support createInstance.");
  60270. };
  60271. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60272. if (!this._geometry) {
  60273. return this;
  60274. }
  60275. // VBOs
  60276. this._geometry._bind(this._colorShader.getEffect());
  60277. // Color
  60278. if (!this.useVertexColor) {
  60279. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60280. }
  60281. return this;
  60282. };
  60283. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60284. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60285. return this;
  60286. }
  60287. var engine = this.getScene().getEngine();
  60288. // Draw order
  60289. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60290. return this;
  60291. };
  60292. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60293. this._colorShader.dispose();
  60294. _super.prototype.dispose.call(this, doNotRecurse);
  60295. };
  60296. /**
  60297. * Returns a new LineMesh object cloned from the current one.
  60298. */
  60299. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60300. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60301. };
  60302. return LinesMesh;
  60303. }(BABYLON.Mesh));
  60304. BABYLON.LinesMesh = LinesMesh;
  60305. })(BABYLON || (BABYLON = {}));
  60306. //# sourceMappingURL=babylon.linesMesh.js.map
  60307. var BABYLON;
  60308. (function (BABYLON) {
  60309. /**
  60310. * Class containing static functions to help procedurally build meshes
  60311. */
  60312. var MeshBuilder = /** @class */ (function () {
  60313. function MeshBuilder() {
  60314. }
  60315. MeshBuilder.updateSideOrientation = function (orientation) {
  60316. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60317. return BABYLON.Mesh.DOUBLESIDE;
  60318. }
  60319. if (orientation === undefined || orientation === null) {
  60320. return BABYLON.Mesh.FRONTSIDE;
  60321. }
  60322. return orientation;
  60323. };
  60324. /**
  60325. * Creates a box mesh
  60326. * * The parameter `size` sets the size (float) of each box side (default 1)
  60327. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60328. * * 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)
  60329. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60330. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60331. * * 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
  60332. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60333. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60334. * @param name defines the name of the mesh
  60335. * @param options defines the options used to create the mesh
  60336. * @param scene defines the hosting scene
  60337. * @returns the box mesh
  60338. */
  60339. MeshBuilder.CreateBox = function (name, options, scene) {
  60340. if (scene === void 0) { scene = null; }
  60341. var box = new BABYLON.Mesh(name, scene);
  60342. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60343. box._originalBuilderSideOrientation = options.sideOrientation;
  60344. var vertexData = BABYLON.VertexData.CreateBox(options);
  60345. vertexData.applyToMesh(box, options.updatable);
  60346. return box;
  60347. };
  60348. /**
  60349. * Creates a sphere mesh
  60350. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60351. * * 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`)
  60352. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60353. * * 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
  60354. * * 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)
  60355. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60356. * * 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
  60357. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60358. * @param name defines the name of the mesh
  60359. * @param options defines the options used to create the mesh
  60360. * @param scene defines the hosting scene
  60361. * @returns the sphere mesh
  60362. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60363. */
  60364. MeshBuilder.CreateSphere = function (name, options, scene) {
  60365. var sphere = new BABYLON.Mesh(name, scene);
  60366. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60367. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60368. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60369. vertexData.applyToMesh(sphere, options.updatable);
  60370. return sphere;
  60371. };
  60372. /**
  60373. * Creates a plane polygonal mesh. By default, this is a disc
  60374. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60375. * * 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
  60376. * * 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
  60377. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60378. * * 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
  60379. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60380. * @param name defines the name of the mesh
  60381. * @param options defines the options used to create the mesh
  60382. * @param scene defines the hosting scene
  60383. * @returns the plane polygonal mesh
  60384. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60385. */
  60386. MeshBuilder.CreateDisc = function (name, options, scene) {
  60387. if (scene === void 0) { scene = null; }
  60388. var disc = new BABYLON.Mesh(name, scene);
  60389. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60390. disc._originalBuilderSideOrientation = options.sideOrientation;
  60391. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60392. vertexData.applyToMesh(disc, options.updatable);
  60393. return disc;
  60394. };
  60395. /**
  60396. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60397. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60398. * * 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`)
  60399. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60400. * * 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
  60401. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60402. * * 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
  60403. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60404. * @param name defines the name of the mesh
  60405. * @param options defines the options used to create the mesh
  60406. * @param scene defines the hosting scene
  60407. * @returns the icosahedron mesh
  60408. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60409. */
  60410. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60411. var sphere = new BABYLON.Mesh(name, scene);
  60412. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60413. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60414. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60415. vertexData.applyToMesh(sphere, options.updatable);
  60416. return sphere;
  60417. };
  60418. ;
  60419. /**
  60420. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60421. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60422. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60423. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60424. * * 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
  60425. * * 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
  60426. * * 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
  60427. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60428. * * 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
  60429. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60430. * * 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
  60431. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60432. * * 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
  60433. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60434. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60435. * @param name defines the name of the mesh
  60436. * @param options defines the options used to create the mesh
  60437. * @param scene defines the hosting scene
  60438. * @returns the ribbon mesh
  60439. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60440. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60441. */
  60442. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60443. if (scene === void 0) { scene = null; }
  60444. var pathArray = options.pathArray;
  60445. var closeArray = options.closeArray;
  60446. var closePath = options.closePath;
  60447. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60448. var instance = options.instance;
  60449. var updatable = options.updatable;
  60450. if (instance) { // existing ribbon instance update
  60451. // positionFunction : ribbon case
  60452. // only pathArray and sideOrientation parameters are taken into account for positions update
  60453. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60454. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60455. var positionFunction = function (positions) {
  60456. var minlg = pathArray[0].length;
  60457. var i = 0;
  60458. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60459. for (var si = 1; si <= ns; si++) {
  60460. for (var p = 0; p < pathArray.length; p++) {
  60461. var path = pathArray[p];
  60462. var l = path.length;
  60463. minlg = (minlg < l) ? minlg : l;
  60464. var j = 0;
  60465. while (j < minlg) {
  60466. positions[i] = path[j].x;
  60467. positions[i + 1] = path[j].y;
  60468. positions[i + 2] = path[j].z;
  60469. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60470. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60471. }
  60472. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60473. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60474. }
  60475. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60476. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60477. }
  60478. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60479. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60480. }
  60481. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60482. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60483. }
  60484. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60485. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60486. }
  60487. j++;
  60488. i += 3;
  60489. }
  60490. if (instance._closePath) {
  60491. positions[i] = path[0].x;
  60492. positions[i + 1] = path[0].y;
  60493. positions[i + 2] = path[0].z;
  60494. i += 3;
  60495. }
  60496. }
  60497. }
  60498. };
  60499. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60500. positionFunction(positions);
  60501. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60502. instance._boundingInfo.update(instance._worldMatrix);
  60503. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60504. if (options.colors) {
  60505. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60506. for (var c = 0; c < options.colors.length; c++) {
  60507. colors[c * 4] = options.colors[c].r;
  60508. colors[c * 4 + 1] = options.colors[c].g;
  60509. colors[c * 4 + 2] = options.colors[c].b;
  60510. colors[c * 4 + 3] = options.colors[c].a;
  60511. }
  60512. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60513. }
  60514. if (options.uvs) {
  60515. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60516. for (var i = 0; i < options.uvs.length; i++) {
  60517. uvs[i * 2] = options.uvs[i].x;
  60518. uvs[i * 2 + 1] = options.uvs[i].y;
  60519. }
  60520. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60521. }
  60522. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60523. var indices = instance.getIndices();
  60524. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60525. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60526. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60527. if (instance._closePath) {
  60528. var indexFirst = 0;
  60529. var indexLast = 0;
  60530. for (var p = 0; p < pathArray.length; p++) {
  60531. indexFirst = instance._idx[p] * 3;
  60532. if (p + 1 < pathArray.length) {
  60533. indexLast = (instance._idx[p + 1] - 1) * 3;
  60534. }
  60535. else {
  60536. indexLast = normals.length - 3;
  60537. }
  60538. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60539. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60540. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60541. normals[indexLast] = normals[indexFirst];
  60542. normals[indexLast + 1] = normals[indexFirst + 1];
  60543. normals[indexLast + 2] = normals[indexFirst + 2];
  60544. }
  60545. }
  60546. if (!(instance.areNormalsFrozen)) {
  60547. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60548. }
  60549. }
  60550. return instance;
  60551. }
  60552. else { // new ribbon creation
  60553. var ribbon = new BABYLON.Mesh(name, scene);
  60554. ribbon._originalBuilderSideOrientation = sideOrientation;
  60555. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60556. if (closePath) {
  60557. ribbon._idx = vertexData._idx;
  60558. }
  60559. ribbon._closePath = closePath;
  60560. ribbon._closeArray = closeArray;
  60561. vertexData.applyToMesh(ribbon, updatable);
  60562. return ribbon;
  60563. }
  60564. };
  60565. /**
  60566. * Creates a cylinder or a cone mesh
  60567. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60568. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60569. * * 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.
  60570. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60571. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60572. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60573. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60574. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60575. * * 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).
  60576. * * 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
  60577. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60578. * * 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
  60579. * * 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.
  60580. * * If `enclose` is false, a ring surface is one element.
  60581. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60582. * * 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
  60583. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60584. * * 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
  60585. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60586. * @param name defines the name of the mesh
  60587. * @param options defines the options used to create the mesh
  60588. * @param scene defines the hosting scene
  60589. * @returns the cylinder mesh
  60590. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60591. */
  60592. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60593. var cylinder = new BABYLON.Mesh(name, scene);
  60594. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60595. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60596. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60597. vertexData.applyToMesh(cylinder, options.updatable);
  60598. return cylinder;
  60599. };
  60600. /**
  60601. * Creates a torus mesh
  60602. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60603. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60604. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60605. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60606. * * 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
  60607. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60608. * @param name defines the name of the mesh
  60609. * @param options defines the options used to create the mesh
  60610. * @param scene defines the hosting scene
  60611. * @returns the torus mesh
  60612. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60613. */
  60614. MeshBuilder.CreateTorus = function (name, options, scene) {
  60615. var torus = new BABYLON.Mesh(name, scene);
  60616. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60617. torus._originalBuilderSideOrientation = options.sideOrientation;
  60618. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60619. vertexData.applyToMesh(torus, options.updatable);
  60620. return torus;
  60621. };
  60622. /**
  60623. * Creates a torus knot mesh
  60624. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60625. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60626. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60627. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60628. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60629. * * 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
  60630. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60631. * @param name defines the name of the mesh
  60632. * @param options defines the options used to create the mesh
  60633. * @param scene defines the hosting scene
  60634. * @returns the torus knot mesh
  60635. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60636. */
  60637. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60638. var torusKnot = new BABYLON.Mesh(name, scene);
  60639. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60640. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60641. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60642. vertexData.applyToMesh(torusKnot, options.updatable);
  60643. return torusKnot;
  60644. };
  60645. /**
  60646. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60647. * * 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
  60648. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60649. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60650. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60651. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60652. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60653. * * 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
  60654. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60655. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60656. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60657. * @param name defines the name of the new line system
  60658. * @param options defines the options used to create the line system
  60659. * @param scene defines the hosting scene
  60660. * @returns a new line system mesh
  60661. */
  60662. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60663. var instance = options.instance;
  60664. var lines = options.lines;
  60665. var colors = options.colors;
  60666. if (instance) { // lines update
  60667. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60668. var vertexColor;
  60669. var lineColors;
  60670. if (colors) {
  60671. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60672. }
  60673. var i = 0;
  60674. var c = 0;
  60675. for (var l = 0; l < lines.length; l++) {
  60676. var points = lines[l];
  60677. for (var p = 0; p < points.length; p++) {
  60678. positions[i] = points[p].x;
  60679. positions[i + 1] = points[p].y;
  60680. positions[i + 2] = points[p].z;
  60681. if (colors && vertexColor) {
  60682. lineColors = colors[l];
  60683. vertexColor[c] = lineColors[p].r;
  60684. vertexColor[c + 1] = lineColors[p].g;
  60685. vertexColor[c + 2] = lineColors[p].b;
  60686. vertexColor[c + 3] = lineColors[p].a;
  60687. c += 4;
  60688. }
  60689. i += 3;
  60690. }
  60691. }
  60692. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60693. if (colors && vertexColor) {
  60694. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60695. }
  60696. return instance;
  60697. }
  60698. // line system creation
  60699. var useVertexColor = (colors) ? true : false;
  60700. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60701. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60702. vertexData.applyToMesh(lineSystem, options.updatable);
  60703. return lineSystem;
  60704. };
  60705. /**
  60706. * Creates a line mesh
  60707. * 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
  60708. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60709. * * The parameter `points` is an array successive Vector3
  60710. * * 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
  60711. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60712. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60713. * * When updating an instance, remember that only point positions can change, not the number of points
  60714. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60715. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60716. * @param name defines the name of the new line system
  60717. * @param options defines the options used to create the line system
  60718. * @param scene defines the hosting scene
  60719. * @returns a new line mesh
  60720. */
  60721. MeshBuilder.CreateLines = function (name, options, scene) {
  60722. if (scene === void 0) { scene = null; }
  60723. var colors = (options.colors) ? [options.colors] : null;
  60724. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60725. return lines;
  60726. };
  60727. /**
  60728. * Creates a dashed line mesh
  60729. * * 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
  60730. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60731. * * The parameter `points` is an array successive Vector3
  60732. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60733. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60734. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60735. * * 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
  60736. * * When updating an instance, remember that only point positions can change, not the number of points
  60737. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60738. * @param name defines the name of the mesh
  60739. * @param options defines the options used to create the mesh
  60740. * @param scene defines the hosting scene
  60741. * @returns the dashed line mesh
  60742. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60743. */
  60744. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60745. if (scene === void 0) { scene = null; }
  60746. var points = options.points;
  60747. var instance = options.instance;
  60748. var gapSize = options.gapSize || 1;
  60749. var dashSize = options.dashSize || 3;
  60750. if (instance) { // dashed lines update
  60751. var positionFunction = function (positions) {
  60752. var curvect = BABYLON.Vector3.Zero();
  60753. var nbSeg = positions.length / 6;
  60754. var lg = 0;
  60755. var nb = 0;
  60756. var shft = 0;
  60757. var dashshft = 0;
  60758. var curshft = 0;
  60759. var p = 0;
  60760. var i = 0;
  60761. var j = 0;
  60762. for (i = 0; i < points.length - 1; i++) {
  60763. points[i + 1].subtractToRef(points[i], curvect);
  60764. lg += curvect.length();
  60765. }
  60766. shft = lg / nbSeg;
  60767. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60768. for (i = 0; i < points.length - 1; i++) {
  60769. points[i + 1].subtractToRef(points[i], curvect);
  60770. nb = Math.floor(curvect.length() / shft);
  60771. curvect.normalize();
  60772. j = 0;
  60773. while (j < nb && p < positions.length) {
  60774. curshft = shft * j;
  60775. positions[p] = points[i].x + curshft * curvect.x;
  60776. positions[p + 1] = points[i].y + curshft * curvect.y;
  60777. positions[p + 2] = points[i].z + curshft * curvect.z;
  60778. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60779. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60780. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60781. p += 6;
  60782. j++;
  60783. }
  60784. }
  60785. while (p < positions.length) {
  60786. positions[p] = points[i].x;
  60787. positions[p + 1] = points[i].y;
  60788. positions[p + 2] = points[i].z;
  60789. p += 3;
  60790. }
  60791. };
  60792. instance.updateMeshPositions(positionFunction, false);
  60793. return instance;
  60794. }
  60795. // dashed lines creation
  60796. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60797. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60798. vertexData.applyToMesh(dashedLines, options.updatable);
  60799. dashedLines.dashSize = dashSize;
  60800. dashedLines.gapSize = gapSize;
  60801. return dashedLines;
  60802. };
  60803. /**
  60804. * 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.
  60805. * * 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.
  60806. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60807. * * 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.
  60808. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60809. * * 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
  60810. * * 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
  60811. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60812. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60813. * * 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
  60814. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60815. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60816. * @param name defines the name of the mesh
  60817. * @param options defines the options used to create the mesh
  60818. * @param scene defines the hosting scene
  60819. * @returns the extruded shape mesh
  60820. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60821. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60822. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60823. */
  60824. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60825. if (scene === void 0) { scene = null; }
  60826. var path = options.path;
  60827. var shape = options.shape;
  60828. var scale = options.scale || 1;
  60829. var rotation = options.rotation || 0;
  60830. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60831. var updatable = options.updatable;
  60832. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60833. var instance = options.instance || null;
  60834. var invertUV = options.invertUV || false;
  60835. 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);
  60836. };
  60837. /**
  60838. * Creates an custom extruded shape mesh.
  60839. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60840. * * 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.
  60841. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60842. * * 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
  60843. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60844. * * 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
  60845. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60846. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60847. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60848. * * 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
  60849. * * 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
  60850. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60851. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60852. * * 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
  60853. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60854. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60855. * @param name defines the name of the mesh
  60856. * @param options defines the options used to create the mesh
  60857. * @param scene defines the hosting scene
  60858. * @returns the custom extruded shape mesh
  60859. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  60860. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60861. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60862. */
  60863. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60864. var path = options.path;
  60865. var shape = options.shape;
  60866. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60867. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60868. var ribbonCloseArray = options.ribbonCloseArray || false;
  60869. var ribbonClosePath = options.ribbonClosePath || false;
  60870. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60871. var updatable = options.updatable;
  60872. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60873. var instance = options.instance;
  60874. var invertUV = options.invertUV || false;
  60875. 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);
  60876. };
  60877. /**
  60878. * Creates lathe mesh.
  60879. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60880. * * 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
  60881. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60882. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60883. * * 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
  60884. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60885. * * 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
  60886. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60887. * * 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
  60888. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60889. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60890. * @param name defines the name of the mesh
  60891. * @param options defines the options used to create the mesh
  60892. * @param scene defines the hosting scene
  60893. * @returns the lathe mesh
  60894. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  60895. */
  60896. MeshBuilder.CreateLathe = function (name, options, scene) {
  60897. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  60898. var closed = (options.closed === undefined) ? true : options.closed;
  60899. var shape = options.shape;
  60900. var radius = options.radius || 1;
  60901. var tessellation = options.tessellation || 64;
  60902. var updatable = options.updatable;
  60903. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60904. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60905. var pi2 = Math.PI * 2;
  60906. var paths = new Array();
  60907. var invertUV = options.invertUV || false;
  60908. var i = 0;
  60909. var p = 0;
  60910. var step = pi2 / tessellation * arc;
  60911. var rotated;
  60912. var path = new Array();
  60913. for (i = 0; i <= tessellation; i++) {
  60914. var path = [];
  60915. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  60916. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  60917. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  60918. }
  60919. for (p = 0; p < shape.length; p++) {
  60920. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  60921. path.push(rotated);
  60922. }
  60923. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  60924. 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));
  60925. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  60926. }
  60927. paths.push(path);
  60928. }
  60929. // lathe ribbon
  60930. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60931. return lathe;
  60932. };
  60933. /**
  60934. * Creates a plane mesh
  60935. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  60936. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  60937. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  60938. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60939. * * 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
  60940. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60941. * @param name defines the name of the mesh
  60942. * @param options defines the options used to create the mesh
  60943. * @param scene defines the hosting scene
  60944. * @returns the plane mesh
  60945. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60946. */
  60947. MeshBuilder.CreatePlane = function (name, options, scene) {
  60948. var plane = new BABYLON.Mesh(name, scene);
  60949. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60950. plane._originalBuilderSideOrientation = options.sideOrientation;
  60951. var vertexData = BABYLON.VertexData.CreatePlane(options);
  60952. vertexData.applyToMesh(plane, options.updatable);
  60953. if (options.sourcePlane) {
  60954. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  60955. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  60956. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  60957. plane.rotate(vectorProduct, product);
  60958. }
  60959. return plane;
  60960. };
  60961. /**
  60962. * Creates a ground mesh
  60963. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  60964. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  60965. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60966. * @param name defines the name of the mesh
  60967. * @param options defines the options used to create the mesh
  60968. * @param scene defines the hosting scene
  60969. * @returns the ground mesh
  60970. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60971. */
  60972. MeshBuilder.CreateGround = function (name, options, scene) {
  60973. var ground = new BABYLON.GroundMesh(name, scene);
  60974. ground._setReady(false);
  60975. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  60976. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  60977. ground._width = options.width || 1;
  60978. ground._height = options.height || 1;
  60979. ground._maxX = ground._width / 2;
  60980. ground._maxZ = ground._height / 2;
  60981. ground._minX = -ground._maxX;
  60982. ground._minZ = -ground._maxZ;
  60983. var vertexData = BABYLON.VertexData.CreateGround(options);
  60984. vertexData.applyToMesh(ground, options.updatable);
  60985. ground._setReady(true);
  60986. return ground;
  60987. };
  60988. /**
  60989. * Creates a tiled ground mesh
  60990. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  60991. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  60992. * * 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
  60993. * * 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
  60994. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60995. * @param name defines the name of the mesh
  60996. * @param options defines the options used to create the mesh
  60997. * @param scene defines the hosting scene
  60998. * @returns the tiled ground mesh
  60999. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61000. */
  61001. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61002. var tiledGround = new BABYLON.Mesh(name, scene);
  61003. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61004. vertexData.applyToMesh(tiledGround, options.updatable);
  61005. return tiledGround;
  61006. };
  61007. /**
  61008. * Creates a ground mesh from a height map
  61009. * * The parameter `url` sets the URL of the height map image resource.
  61010. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61011. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61012. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61013. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61014. * * 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.
  61015. * * 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).
  61016. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61017. * @param name defines the name of the mesh
  61018. * @param url defines the url to the height map
  61019. * @param options defines the options used to create the mesh
  61020. * @param scene defines the hosting scene
  61021. * @returns the ground mesh
  61022. * @see http://doc.babylonjs.com/babylon101/height_map
  61023. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61024. */
  61025. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61026. var width = options.width || 10.0;
  61027. var height = options.height || 10.0;
  61028. var subdivisions = options.subdivisions || 1 | 0;
  61029. var minHeight = options.minHeight || 0.0;
  61030. var maxHeight = options.maxHeight || 1.0;
  61031. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61032. var updatable = options.updatable;
  61033. var onReady = options.onReady;
  61034. var ground = new BABYLON.GroundMesh(name, scene);
  61035. ground._subdivisionsX = subdivisions;
  61036. ground._subdivisionsY = subdivisions;
  61037. ground._width = width;
  61038. ground._height = height;
  61039. ground._maxX = ground._width / 2.0;
  61040. ground._maxZ = ground._height / 2.0;
  61041. ground._minX = -ground._maxX;
  61042. ground._minZ = -ground._maxZ;
  61043. ground._setReady(false);
  61044. var onload = function (img) {
  61045. // Getting height map data
  61046. var canvas = document.createElement("canvas");
  61047. var context = canvas.getContext("2d");
  61048. if (!context) {
  61049. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61050. }
  61051. if (scene.isDisposed) {
  61052. return;
  61053. }
  61054. var bufferWidth = img.width;
  61055. var bufferHeight = img.height;
  61056. canvas.width = bufferWidth;
  61057. canvas.height = bufferHeight;
  61058. context.drawImage(img, 0, 0);
  61059. // Create VertexData from map data
  61060. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61061. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61062. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61063. width: width, height: height,
  61064. subdivisions: subdivisions,
  61065. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61066. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61067. });
  61068. vertexData.applyToMesh(ground, updatable);
  61069. //execute ready callback, if set
  61070. if (onReady) {
  61071. onReady(ground);
  61072. }
  61073. ground._setReady(true);
  61074. };
  61075. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61076. return ground;
  61077. };
  61078. /**
  61079. * Creates a polygon mesh
  61080. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61081. * * 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
  61082. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61083. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61084. * * 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)
  61085. * * Remember you can only change the shape positions, not their number when updating a polygon
  61086. * @param name defines the name of the mesh
  61087. * @param options defines the options used to create the mesh
  61088. * @param scene defines the hosting scene
  61089. * @returns the polygon mesh
  61090. */
  61091. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61092. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61093. var shape = options.shape;
  61094. var holes = options.holes || [];
  61095. var depth = options.depth || 0;
  61096. var contours = [];
  61097. var hole = [];
  61098. for (var i = 0; i < shape.length; i++) {
  61099. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61100. }
  61101. var epsilon = 0.00000001;
  61102. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61103. contours.pop();
  61104. }
  61105. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61106. for (var hNb = 0; hNb < holes.length; hNb++) {
  61107. hole = [];
  61108. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61109. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61110. }
  61111. polygonTriangulation.addHole(hole);
  61112. }
  61113. var polygon = polygonTriangulation.build(options.updatable, depth);
  61114. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61115. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61116. vertexData.applyToMesh(polygon, options.updatable);
  61117. return polygon;
  61118. };
  61119. ;
  61120. /**
  61121. * Creates an extruded polygon mesh, with depth in the Y direction.
  61122. * * 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)
  61123. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61124. * @param name defines the name of the mesh
  61125. * @param options defines the options used to create the mesh
  61126. * @param scene defines the hosting scene
  61127. * @returns the polygon mesh
  61128. */
  61129. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61130. return MeshBuilder.CreatePolygon(name, options, scene);
  61131. };
  61132. ;
  61133. /**
  61134. * Creates a tube mesh.
  61135. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61136. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61137. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61138. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61139. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61140. * * 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)
  61141. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61142. * * 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
  61143. * * 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
  61144. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61145. * * 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
  61146. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61147. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61148. * @param name defines the name of the mesh
  61149. * @param options defines the options used to create the mesh
  61150. * @param scene defines the hosting scene
  61151. * @returns the tube mesh
  61152. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61153. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61154. */
  61155. MeshBuilder.CreateTube = function (name, options, scene) {
  61156. var path = options.path;
  61157. var instance = options.instance;
  61158. var radius = 1.0;
  61159. if (instance) {
  61160. radius = instance.radius;
  61161. }
  61162. if (options.radius !== undefined) {
  61163. radius = options.radius;
  61164. }
  61165. ;
  61166. var tessellation = options.tessellation || 64 | 0;
  61167. var radiusFunction = options.radiusFunction || null;
  61168. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61169. var invertUV = options.invertUV || false;
  61170. var updatable = options.updatable;
  61171. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61172. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61173. // tube geometry
  61174. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61175. var tangents = path3D.getTangents();
  61176. var normals = path3D.getNormals();
  61177. var distances = path3D.getDistances();
  61178. var pi2 = Math.PI * 2;
  61179. var step = pi2 / tessellation * arc;
  61180. var returnRadius = function () { return radius; };
  61181. var radiusFunctionFinal = radiusFunction || returnRadius;
  61182. var circlePath;
  61183. var rad;
  61184. var normal;
  61185. var rotated;
  61186. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61187. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61188. for (var i = 0; i < path.length; i++) {
  61189. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61190. circlePath = Array(); // current circle array
  61191. normal = normals[i]; // current normal
  61192. for (var t = 0; t < tessellation; t++) {
  61193. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61194. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61195. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61196. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61197. circlePath[t] = rotated;
  61198. }
  61199. circlePaths[index] = circlePath;
  61200. index++;
  61201. }
  61202. // cap
  61203. var capPath = function (nbPoints, pathIndex) {
  61204. var pointCap = Array();
  61205. for (var i = 0; i < nbPoints; i++) {
  61206. pointCap.push(path[pathIndex]);
  61207. }
  61208. return pointCap;
  61209. };
  61210. switch (cap) {
  61211. case BABYLON.Mesh.NO_CAP:
  61212. break;
  61213. case BABYLON.Mesh.CAP_START:
  61214. circlePaths[0] = capPath(tessellation, 0);
  61215. circlePaths[1] = circlePaths[2].slice(0);
  61216. break;
  61217. case BABYLON.Mesh.CAP_END:
  61218. circlePaths[index] = circlePaths[index - 1].slice(0);
  61219. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61220. break;
  61221. case BABYLON.Mesh.CAP_ALL:
  61222. circlePaths[0] = capPath(tessellation, 0);
  61223. circlePaths[1] = circlePaths[2].slice(0);
  61224. circlePaths[index] = circlePaths[index - 1].slice(0);
  61225. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61226. break;
  61227. default:
  61228. break;
  61229. }
  61230. return circlePaths;
  61231. };
  61232. var path3D;
  61233. var pathArray;
  61234. if (instance) { // tube update
  61235. var arc = options.arc || instance.arc;
  61236. path3D = (instance.path3D).update(path);
  61237. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61238. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61239. instance.path3D = path3D;
  61240. instance.pathArray = pathArray;
  61241. instance.arc = arc;
  61242. instance.radius = radius;
  61243. return instance;
  61244. }
  61245. // tube creation
  61246. path3D = new BABYLON.Path3D(path);
  61247. var newPathArray = new Array();
  61248. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61249. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61250. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61251. tube.pathArray = pathArray;
  61252. tube.path3D = path3D;
  61253. tube.tessellation = tessellation;
  61254. tube.cap = cap;
  61255. tube.arc = options.arc;
  61256. tube.radius = radius;
  61257. return tube;
  61258. };
  61259. /**
  61260. * Creates a polyhedron mesh
  61261. * * 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
  61262. * * The parameter `size` (positive float, default 1) sets the polygon size
  61263. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61264. * * 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`
  61265. * * 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
  61266. * * 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)`)
  61267. * * 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
  61268. * * 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
  61269. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61270. * * 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
  61271. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61272. * @param name defines the name of the mesh
  61273. * @param options defines the options used to create the mesh
  61274. * @param scene defines the hosting scene
  61275. * @returns the polyhedron mesh
  61276. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61277. */
  61278. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61279. var polyhedron = new BABYLON.Mesh(name, scene);
  61280. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61281. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61282. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61283. vertexData.applyToMesh(polyhedron, options.updatable);
  61284. return polyhedron;
  61285. };
  61286. /**
  61287. * Creates a decal mesh.
  61288. * 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
  61289. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61290. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61291. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61292. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61293. * @param name defines the name of the mesh
  61294. * @param sourceMesh defines the mesh where the decal must be applied
  61295. * @param options defines the options used to create the mesh
  61296. * @param scene defines the hosting scene
  61297. * @returns the decal mesh
  61298. * @see http://doc.babylonjs.com/how_to/decals
  61299. */
  61300. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61301. var indices = sourceMesh.getIndices();
  61302. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61303. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61304. var position = options.position || BABYLON.Vector3.Zero();
  61305. var normal = options.normal || BABYLON.Vector3.Up();
  61306. var size = options.size || BABYLON.Vector3.One();
  61307. var angle = options.angle || 0;
  61308. // Getting correct rotation
  61309. if (!normal) {
  61310. var target = new BABYLON.Vector3(0, 0, 1);
  61311. var camera = sourceMesh.getScene().activeCamera;
  61312. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61313. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61314. }
  61315. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61316. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61317. var pitch = Math.atan2(normal.y, len);
  61318. // Matrix
  61319. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61320. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61321. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61322. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61323. var vertexData = new BABYLON.VertexData();
  61324. vertexData.indices = [];
  61325. vertexData.positions = [];
  61326. vertexData.normals = [];
  61327. vertexData.uvs = [];
  61328. var currentVertexDataIndex = 0;
  61329. var extractDecalVector3 = function (indexId) {
  61330. var result = new BABYLON.PositionNormalVertex();
  61331. if (!indices || !positions || !normals) {
  61332. return result;
  61333. }
  61334. var vertexId = indices[indexId];
  61335. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61336. // Send vector to decal local world
  61337. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61338. // Get normal
  61339. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61340. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61341. return result;
  61342. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61343. var clip = function (vertices, axis) {
  61344. if (vertices.length === 0) {
  61345. return vertices;
  61346. }
  61347. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61348. var clipVertices = function (v0, v1) {
  61349. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61350. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61351. };
  61352. var result = new Array();
  61353. for (var index = 0; index < vertices.length; index += 3) {
  61354. var v1Out;
  61355. var v2Out;
  61356. var v3Out;
  61357. var total = 0;
  61358. var nV1 = null;
  61359. var nV2 = null;
  61360. var nV3 = null;
  61361. var nV4 = null;
  61362. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61363. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61364. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61365. v1Out = d1 > 0;
  61366. v2Out = d2 > 0;
  61367. v3Out = d3 > 0;
  61368. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61369. switch (total) {
  61370. case 0:
  61371. result.push(vertices[index]);
  61372. result.push(vertices[index + 1]);
  61373. result.push(vertices[index + 2]);
  61374. break;
  61375. case 1:
  61376. if (v1Out) {
  61377. nV1 = vertices[index + 1];
  61378. nV2 = vertices[index + 2];
  61379. nV3 = clipVertices(vertices[index], nV1);
  61380. nV4 = clipVertices(vertices[index], nV2);
  61381. }
  61382. if (v2Out) {
  61383. nV1 = vertices[index];
  61384. nV2 = vertices[index + 2];
  61385. nV3 = clipVertices(vertices[index + 1], nV1);
  61386. nV4 = clipVertices(vertices[index + 1], nV2);
  61387. result.push(nV3);
  61388. result.push(nV2.clone());
  61389. result.push(nV1.clone());
  61390. result.push(nV2.clone());
  61391. result.push(nV3.clone());
  61392. result.push(nV4);
  61393. break;
  61394. }
  61395. if (v3Out) {
  61396. nV1 = vertices[index];
  61397. nV2 = vertices[index + 1];
  61398. nV3 = clipVertices(vertices[index + 2], nV1);
  61399. nV4 = clipVertices(vertices[index + 2], nV2);
  61400. }
  61401. if (nV1 && nV2 && nV3 && nV4) {
  61402. result.push(nV1.clone());
  61403. result.push(nV2.clone());
  61404. result.push(nV3);
  61405. result.push(nV4);
  61406. result.push(nV3.clone());
  61407. result.push(nV2.clone());
  61408. }
  61409. break;
  61410. case 2:
  61411. if (!v1Out) {
  61412. nV1 = vertices[index].clone();
  61413. nV2 = clipVertices(nV1, vertices[index + 1]);
  61414. nV3 = clipVertices(nV1, vertices[index + 2]);
  61415. result.push(nV1);
  61416. result.push(nV2);
  61417. result.push(nV3);
  61418. }
  61419. if (!v2Out) {
  61420. nV1 = vertices[index + 1].clone();
  61421. nV2 = clipVertices(nV1, vertices[index + 2]);
  61422. nV3 = clipVertices(nV1, vertices[index]);
  61423. result.push(nV1);
  61424. result.push(nV2);
  61425. result.push(nV3);
  61426. }
  61427. if (!v3Out) {
  61428. nV1 = vertices[index + 2].clone();
  61429. nV2 = clipVertices(nV1, vertices[index]);
  61430. nV3 = clipVertices(nV1, vertices[index + 1]);
  61431. result.push(nV1);
  61432. result.push(nV2);
  61433. result.push(nV3);
  61434. }
  61435. break;
  61436. case 3:
  61437. break;
  61438. }
  61439. }
  61440. return result;
  61441. };
  61442. for (var index = 0; index < indices.length; index += 3) {
  61443. var faceVertices = new Array();
  61444. faceVertices.push(extractDecalVector3(index));
  61445. faceVertices.push(extractDecalVector3(index + 1));
  61446. faceVertices.push(extractDecalVector3(index + 2));
  61447. // Clip
  61448. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61449. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61450. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61451. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61452. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61453. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61454. if (faceVertices.length === 0) {
  61455. continue;
  61456. }
  61457. // Add UVs and get back to world
  61458. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61459. var vertex = faceVertices[vIndex];
  61460. //TODO check for Int32Array | Uint32Array | Uint16Array
  61461. vertexData.indices.push(currentVertexDataIndex);
  61462. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61463. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61464. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61465. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61466. currentVertexDataIndex++;
  61467. }
  61468. }
  61469. // Return mesh
  61470. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61471. vertexData.applyToMesh(decal);
  61472. decal.position = position.clone();
  61473. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61474. return decal;
  61475. };
  61476. // Privates
  61477. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61478. // extrusion geometry
  61479. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61480. var tangents = path3D.getTangents();
  61481. var normals = path3D.getNormals();
  61482. var binormals = path3D.getBinormals();
  61483. var distances = path3D.getDistances();
  61484. var angle = 0;
  61485. var returnScale = function () { return scale !== null ? scale : 1; };
  61486. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61487. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61488. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61489. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61490. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61491. for (var i = 0; i < curve.length; i++) {
  61492. var shapePath = new Array();
  61493. var angleStep = rotate(i, distances[i]);
  61494. var scaleRatio = scl(i, distances[i]);
  61495. for (var p = 0; p < shape.length; p++) {
  61496. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61497. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61498. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61499. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61500. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61501. shapePath[p] = rotated;
  61502. }
  61503. shapePaths[index] = shapePath;
  61504. angle += angleStep;
  61505. index++;
  61506. }
  61507. // cap
  61508. var capPath = function (shapePath) {
  61509. var pointCap = Array();
  61510. var barycenter = BABYLON.Vector3.Zero();
  61511. var i;
  61512. for (i = 0; i < shapePath.length; i++) {
  61513. barycenter.addInPlace(shapePath[i]);
  61514. }
  61515. barycenter.scaleInPlace(1.0 / shapePath.length);
  61516. for (i = 0; i < shapePath.length; i++) {
  61517. pointCap.push(barycenter);
  61518. }
  61519. return pointCap;
  61520. };
  61521. switch (cap) {
  61522. case BABYLON.Mesh.NO_CAP:
  61523. break;
  61524. case BABYLON.Mesh.CAP_START:
  61525. shapePaths[0] = capPath(shapePaths[2]);
  61526. shapePaths[1] = shapePaths[2];
  61527. break;
  61528. case BABYLON.Mesh.CAP_END:
  61529. shapePaths[index] = shapePaths[index - 1];
  61530. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61531. break;
  61532. case BABYLON.Mesh.CAP_ALL:
  61533. shapePaths[0] = capPath(shapePaths[2]);
  61534. shapePaths[1] = shapePaths[2];
  61535. shapePaths[index] = shapePaths[index - 1];
  61536. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61537. break;
  61538. default:
  61539. break;
  61540. }
  61541. return shapePaths;
  61542. };
  61543. var path3D;
  61544. var pathArray;
  61545. if (instance) { // instance update
  61546. path3D = (instance.path3D).update(curve);
  61547. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61548. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61549. return instance;
  61550. }
  61551. // extruded shape creation
  61552. path3D = new BABYLON.Path3D(curve);
  61553. var newShapePaths = new Array();
  61554. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61555. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61556. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61557. extrudedGeneric.pathArray = pathArray;
  61558. extrudedGeneric.path3D = path3D;
  61559. extrudedGeneric.cap = cap;
  61560. return extrudedGeneric;
  61561. };
  61562. return MeshBuilder;
  61563. }());
  61564. BABYLON.MeshBuilder = MeshBuilder;
  61565. })(BABYLON || (BABYLON = {}));
  61566. //# sourceMappingURL=babylon.meshBuilder.js.map
  61567. var BABYLON;
  61568. (function (BABYLON) {
  61569. /**
  61570. * Draco compression (https://google.github.io/draco/)
  61571. *
  61572. * This class wraps the Draco module.
  61573. *
  61574. * **Encoder**
  61575. *
  61576. * The encoder is not currently implemented.
  61577. *
  61578. * **Decoder**
  61579. *
  61580. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  61581. *
  61582. * To update the configuration, use the following code:
  61583. * ```javascript
  61584. * BABYLON.DracoCompression.Configuration = {
  61585. * decoder: {
  61586. * wasmUrl: "<url to the WebAssembly library>",
  61587. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  61588. * fallbackUrl: "<url to the fallback JavaScript library>",
  61589. * }
  61590. * };
  61591. * ```
  61592. *
  61593. * 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.
  61594. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  61595. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  61596. *
  61597. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  61598. * ```javascript
  61599. * var dracoCompression = new BABYLON.DracoCompression();
  61600. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  61601. * [BABYLON.VertexBuffer.PositionKind]: 0
  61602. * });
  61603. * ```
  61604. *
  61605. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  61606. */
  61607. var DracoCompression = /** @class */ (function () {
  61608. /**
  61609. * Constructor
  61610. */
  61611. function DracoCompression() {
  61612. }
  61613. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61614. /**
  61615. * Returns true if the decoder is available.
  61616. */
  61617. get: function () {
  61618. if (typeof DracoDecoderModule !== "undefined") {
  61619. return true;
  61620. }
  61621. var decoder = DracoCompression.Configuration.decoder;
  61622. if (decoder) {
  61623. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61624. return true;
  61625. }
  61626. if (decoder.fallbackUrl) {
  61627. return true;
  61628. }
  61629. }
  61630. return false;
  61631. },
  61632. enumerable: true,
  61633. configurable: true
  61634. });
  61635. /**
  61636. * Stop all async operations and release resources.
  61637. */
  61638. DracoCompression.prototype.dispose = function () {
  61639. };
  61640. /**
  61641. * Decode Draco compressed mesh data to vertex data.
  61642. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  61643. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61644. * @returns A promise that resolves with the decoded vertex data
  61645. */
  61646. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61647. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  61648. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61649. var module = wrappedModule.module;
  61650. var vertexData = new BABYLON.VertexData();
  61651. var buffer = new module.DecoderBuffer();
  61652. buffer.Init(dataView, dataView.byteLength);
  61653. var decoder = new module.Decoder();
  61654. var geometry;
  61655. var status;
  61656. try {
  61657. var type = decoder.GetEncodedGeometryType(buffer);
  61658. switch (type) {
  61659. case module.TRIANGULAR_MESH:
  61660. geometry = new module.Mesh();
  61661. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61662. break;
  61663. case module.POINT_CLOUD:
  61664. geometry = new module.PointCloud();
  61665. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61666. break;
  61667. default:
  61668. throw new Error("Invalid geometry type " + type);
  61669. }
  61670. if (!status.ok() || !geometry.ptr) {
  61671. throw new Error(status.error_msg());
  61672. }
  61673. var numPoints = geometry.num_points();
  61674. if (type === module.TRIANGULAR_MESH) {
  61675. var numFaces = geometry.num_faces();
  61676. var faceIndices = new module.DracoInt32Array();
  61677. try {
  61678. var indices = new Uint32Array(numFaces * 3);
  61679. for (var i = 0; i < numFaces; i++) {
  61680. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61681. var offset = i * 3;
  61682. indices[offset + 0] = faceIndices.GetValue(0);
  61683. indices[offset + 1] = faceIndices.GetValue(1);
  61684. indices[offset + 2] = faceIndices.GetValue(2);
  61685. }
  61686. vertexData.indices = indices;
  61687. }
  61688. finally {
  61689. module.destroy(faceIndices);
  61690. }
  61691. }
  61692. for (var kind in attributes) {
  61693. var uniqueId = attributes[kind];
  61694. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61695. var dracoData = new module.DracoFloat32Array();
  61696. try {
  61697. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61698. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61699. for (var i = 0; i < babylonData.length; i++) {
  61700. babylonData[i] = dracoData.GetValue(i);
  61701. }
  61702. vertexData.set(babylonData, kind);
  61703. }
  61704. finally {
  61705. module.destroy(dracoData);
  61706. }
  61707. }
  61708. }
  61709. finally {
  61710. if (geometry) {
  61711. module.destroy(geometry);
  61712. }
  61713. module.destroy(decoder);
  61714. module.destroy(buffer);
  61715. }
  61716. return vertexData;
  61717. });
  61718. };
  61719. DracoCompression._GetDecoderModule = function () {
  61720. if (!DracoCompression._DecoderModulePromise) {
  61721. var promise = null;
  61722. var config_1 = {};
  61723. if (typeof DracoDecoderModule !== "undefined") {
  61724. promise = Promise.resolve();
  61725. }
  61726. else {
  61727. var decoder = DracoCompression.Configuration.decoder;
  61728. if (decoder) {
  61729. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61730. promise = Promise.all([
  61731. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61732. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61733. config_1.wasmBinary = data;
  61734. })
  61735. ]);
  61736. }
  61737. else if (decoder.fallbackUrl) {
  61738. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61739. }
  61740. }
  61741. }
  61742. if (!promise) {
  61743. throw new Error("Draco decoder module is not available");
  61744. }
  61745. DracoCompression._DecoderModulePromise = promise.then(function () {
  61746. return new Promise(function (resolve) {
  61747. config_1.onModuleLoaded = function (decoderModule) {
  61748. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61749. resolve({ module: decoderModule });
  61750. };
  61751. DracoDecoderModule(config_1);
  61752. });
  61753. });
  61754. }
  61755. return DracoCompression._DecoderModulePromise;
  61756. };
  61757. DracoCompression._LoadScriptAsync = function (url) {
  61758. return new Promise(function (resolve, reject) {
  61759. BABYLON.Tools.LoadScript(url, function () {
  61760. resolve();
  61761. }, function (message) {
  61762. reject(new Error(message));
  61763. });
  61764. });
  61765. };
  61766. DracoCompression._LoadFileAsync = function (url) {
  61767. return new Promise(function (resolve, reject) {
  61768. BABYLON.Tools.LoadFile(url, function (data) {
  61769. resolve(data);
  61770. }, undefined, undefined, true, function (request, exception) {
  61771. reject(exception);
  61772. });
  61773. });
  61774. };
  61775. /**
  61776. * The configuration. Defaults to the following urls:
  61777. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  61778. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  61779. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61780. */
  61781. DracoCompression.Configuration = {
  61782. decoder: {
  61783. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61784. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61785. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61786. }
  61787. };
  61788. return DracoCompression;
  61789. }());
  61790. BABYLON.DracoCompression = DracoCompression;
  61791. })(BABYLON || (BABYLON = {}));
  61792. //# sourceMappingURL=babylon.dracoCompression.js.map
  61793. var BABYLON;
  61794. (function (BABYLON) {
  61795. var AudioEngine = /** @class */ (function () {
  61796. function AudioEngine() {
  61797. this._audioContext = null;
  61798. this._audioContextInitialized = false;
  61799. this.canUseWebAudio = false;
  61800. this.WarnedWebAudioUnsupported = false;
  61801. this.unlocked = false;
  61802. this.isMP3supported = false;
  61803. this.isOGGsupported = false;
  61804. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61805. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61806. this.canUseWebAudio = true;
  61807. }
  61808. var audioElem = document.createElement('audio');
  61809. try {
  61810. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61811. this.isMP3supported = true;
  61812. }
  61813. }
  61814. catch (e) {
  61815. // protect error during capability check.
  61816. }
  61817. try {
  61818. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61819. this.isOGGsupported = true;
  61820. }
  61821. }
  61822. catch (e) {
  61823. // protect error during capability check.
  61824. }
  61825. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61826. this._unlockiOSaudio();
  61827. }
  61828. else {
  61829. this.unlocked = true;
  61830. }
  61831. }
  61832. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61833. get: function () {
  61834. if (!this._audioContextInitialized) {
  61835. this._initializeAudioContext();
  61836. }
  61837. return this._audioContext;
  61838. },
  61839. enumerable: true,
  61840. configurable: true
  61841. });
  61842. AudioEngine.prototype._unlockiOSaudio = function () {
  61843. var _this = this;
  61844. var unlockaudio = function () {
  61845. if (!_this.audioContext) {
  61846. return;
  61847. }
  61848. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61849. var source = _this.audioContext.createBufferSource();
  61850. source.buffer = buffer;
  61851. source.connect(_this.audioContext.destination);
  61852. source.start(0);
  61853. setTimeout(function () {
  61854. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61855. _this.unlocked = true;
  61856. window.removeEventListener('touchend', unlockaudio, false);
  61857. if (_this.onAudioUnlocked) {
  61858. _this.onAudioUnlocked();
  61859. }
  61860. }
  61861. }, 0);
  61862. };
  61863. window.addEventListener('touchend', unlockaudio, false);
  61864. };
  61865. AudioEngine.prototype._initializeAudioContext = function () {
  61866. try {
  61867. if (this.canUseWebAudio) {
  61868. this._audioContext = new AudioContext();
  61869. // create a global volume gain node
  61870. this.masterGain = this._audioContext.createGain();
  61871. this.masterGain.gain.value = 1;
  61872. this.masterGain.connect(this._audioContext.destination);
  61873. this._audioContextInitialized = true;
  61874. }
  61875. }
  61876. catch (e) {
  61877. this.canUseWebAudio = false;
  61878. BABYLON.Tools.Error("Web Audio: " + e.message);
  61879. }
  61880. };
  61881. AudioEngine.prototype.dispose = function () {
  61882. if (this.canUseWebAudio && this._audioContextInitialized) {
  61883. if (this._connectedAnalyser && this._audioContext) {
  61884. this._connectedAnalyser.stopDebugCanvas();
  61885. this._connectedAnalyser.dispose();
  61886. this.masterGain.disconnect();
  61887. this.masterGain.connect(this._audioContext.destination);
  61888. this._connectedAnalyser = null;
  61889. }
  61890. this.masterGain.gain.value = 1;
  61891. }
  61892. this.WarnedWebAudioUnsupported = false;
  61893. };
  61894. AudioEngine.prototype.getGlobalVolume = function () {
  61895. if (this.canUseWebAudio && this._audioContextInitialized) {
  61896. return this.masterGain.gain.value;
  61897. }
  61898. else {
  61899. return -1;
  61900. }
  61901. };
  61902. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61903. if (this.canUseWebAudio && this._audioContextInitialized) {
  61904. this.masterGain.gain.value = newVolume;
  61905. }
  61906. };
  61907. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61908. if (this._connectedAnalyser) {
  61909. this._connectedAnalyser.stopDebugCanvas();
  61910. }
  61911. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61912. this._connectedAnalyser = analyser;
  61913. this.masterGain.disconnect();
  61914. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61915. }
  61916. };
  61917. return AudioEngine;
  61918. }());
  61919. BABYLON.AudioEngine = AudioEngine;
  61920. })(BABYLON || (BABYLON = {}));
  61921. //# sourceMappingURL=babylon.audioEngine.js.map
  61922. var BABYLON;
  61923. (function (BABYLON) {
  61924. var Sound = /** @class */ (function () {
  61925. /**
  61926. * Create a sound and attach it to a scene
  61927. * @param name Name of your sound
  61928. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  61929. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  61930. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  61931. */
  61932. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  61933. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  61934. var _this = this;
  61935. this.autoplay = false;
  61936. this.loop = false;
  61937. this.useCustomAttenuation = false;
  61938. this.spatialSound = false;
  61939. this.refDistance = 1;
  61940. this.rolloffFactor = 1;
  61941. this.maxDistance = 100;
  61942. this.distanceModel = "linear";
  61943. this._panningModel = "equalpower";
  61944. this._playbackRate = 1;
  61945. this._streaming = false;
  61946. this._startTime = 0;
  61947. this._startOffset = 0;
  61948. this._position = BABYLON.Vector3.Zero();
  61949. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  61950. this._volume = 1;
  61951. this._isReadyToPlay = false;
  61952. this.isPlaying = false;
  61953. this.isPaused = false;
  61954. this._isDirectional = false;
  61955. // Used if you'd like to create a directional sound.
  61956. // If not set, the sound will be omnidirectional
  61957. this._coneInnerAngle = 360;
  61958. this._coneOuterAngle = 360;
  61959. this._coneOuterGain = 0;
  61960. this._isOutputConnected = false;
  61961. this._urlType = "Unknown";
  61962. this.name = name;
  61963. this._scene = scene;
  61964. this._readyToPlayCallback = readyToPlayCallback;
  61965. // Default custom attenuation function is a linear attenuation
  61966. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  61967. if (currentDistance < maxDistance) {
  61968. return currentVolume * (1 - currentDistance / maxDistance);
  61969. }
  61970. else {
  61971. return 0;
  61972. }
  61973. };
  61974. if (options) {
  61975. this.autoplay = options.autoplay || false;
  61976. this.loop = options.loop || false;
  61977. // if volume === 0, we need another way to check this option
  61978. if (options.volume !== undefined) {
  61979. this._volume = options.volume;
  61980. }
  61981. this.spatialSound = options.spatialSound || false;
  61982. this.maxDistance = options.maxDistance || 100;
  61983. this.useCustomAttenuation = options.useCustomAttenuation || false;
  61984. this.rolloffFactor = options.rolloffFactor || 1;
  61985. this.refDistance = options.refDistance || 1;
  61986. this.distanceModel = options.distanceModel || "linear";
  61987. this._playbackRate = options.playbackRate || 1;
  61988. this._streaming = options.streaming || false;
  61989. }
  61990. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61991. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  61992. this._soundGain.gain.value = this._volume;
  61993. this._inputAudioNode = this._soundGain;
  61994. this._ouputAudioNode = this._soundGain;
  61995. if (this.spatialSound) {
  61996. this._createSpatialParameters();
  61997. }
  61998. this._scene.mainSoundTrack.AddSound(this);
  61999. var validParameter = true;
  62000. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62001. if (urlOrArrayBuffer) {
  62002. try {
  62003. if (typeof (urlOrArrayBuffer) === "string") {
  62004. this._urlType = "String";
  62005. }
  62006. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  62007. this._urlType = "ArrayBuffer";
  62008. }
  62009. else if (urlOrArrayBuffer instanceof MediaStream) {
  62010. this._urlType = "MediaStream";
  62011. }
  62012. else if (Array.isArray(urlOrArrayBuffer)) {
  62013. this._urlType = "Array";
  62014. }
  62015. var urls = [];
  62016. var codecSupportedFound = false;
  62017. switch (this._urlType) {
  62018. case "MediaStream":
  62019. this._streaming = true;
  62020. this._isReadyToPlay = true;
  62021. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  62022. if (this.autoplay) {
  62023. this.play();
  62024. }
  62025. if (this._readyToPlayCallback) {
  62026. this._readyToPlayCallback();
  62027. }
  62028. break;
  62029. case "ArrayBuffer":
  62030. if (urlOrArrayBuffer.byteLength > 0) {
  62031. codecSupportedFound = true;
  62032. this._soundLoaded(urlOrArrayBuffer);
  62033. }
  62034. break;
  62035. case "String":
  62036. urls.push(urlOrArrayBuffer);
  62037. case "Array":
  62038. if (urls.length === 0)
  62039. urls = urlOrArrayBuffer;
  62040. // If we found a supported format, we load it immediately and stop the loop
  62041. for (var i = 0; i < urls.length; i++) {
  62042. var url = urls[i];
  62043. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62044. codecSupportedFound = true;
  62045. }
  62046. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62047. codecSupportedFound = true;
  62048. }
  62049. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62050. codecSupportedFound = true;
  62051. }
  62052. if (url.indexOf("blob:") !== -1) {
  62053. codecSupportedFound = true;
  62054. }
  62055. if (codecSupportedFound) {
  62056. // Loading sound using XHR2
  62057. if (!this._streaming) {
  62058. this._scene._loadFile(url, function (data) {
  62059. _this._soundLoaded(data);
  62060. }, undefined, true, true, function (exception) {
  62061. if (exception) {
  62062. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62063. }
  62064. BABYLON.Tools.Error("Sound creation aborted.");
  62065. _this._scene.mainSoundTrack.RemoveSound(_this);
  62066. });
  62067. }
  62068. // Streaming sound using HTML5 Audio tag
  62069. else {
  62070. this._htmlAudioElement = new Audio(url);
  62071. this._htmlAudioElement.controls = false;
  62072. this._htmlAudioElement.loop = this.loop;
  62073. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62074. this._htmlAudioElement.preload = "auto";
  62075. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62076. _this._isReadyToPlay = true;
  62077. if (_this.autoplay) {
  62078. _this.play();
  62079. }
  62080. if (_this._readyToPlayCallback) {
  62081. _this._readyToPlayCallback();
  62082. }
  62083. });
  62084. document.body.appendChild(this._htmlAudioElement);
  62085. }
  62086. break;
  62087. }
  62088. }
  62089. break;
  62090. default:
  62091. validParameter = false;
  62092. break;
  62093. }
  62094. if (!validParameter) {
  62095. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62096. }
  62097. else {
  62098. if (!codecSupportedFound) {
  62099. this._isReadyToPlay = true;
  62100. // Simulating a ready to play event to avoid breaking code path
  62101. if (this._readyToPlayCallback) {
  62102. window.setTimeout(function () {
  62103. if (_this._readyToPlayCallback) {
  62104. _this._readyToPlayCallback();
  62105. }
  62106. }, 1000);
  62107. }
  62108. }
  62109. }
  62110. }
  62111. catch (ex) {
  62112. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62113. this._scene.mainSoundTrack.RemoveSound(this);
  62114. }
  62115. }
  62116. }
  62117. else {
  62118. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62119. this._scene.mainSoundTrack.AddSound(this);
  62120. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62121. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62122. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62123. }
  62124. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62125. if (this._readyToPlayCallback) {
  62126. window.setTimeout(function () {
  62127. if (_this._readyToPlayCallback) {
  62128. _this._readyToPlayCallback();
  62129. }
  62130. }, 1000);
  62131. }
  62132. }
  62133. }
  62134. Sound.prototype.dispose = function () {
  62135. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62136. if (this.isPlaying) {
  62137. this.stop();
  62138. }
  62139. this._isReadyToPlay = false;
  62140. if (this.soundTrackId === -1) {
  62141. this._scene.mainSoundTrack.RemoveSound(this);
  62142. }
  62143. else {
  62144. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62145. }
  62146. if (this._soundGain) {
  62147. this._soundGain.disconnect();
  62148. this._soundGain = null;
  62149. }
  62150. if (this._soundPanner) {
  62151. this._soundPanner.disconnect();
  62152. this._soundPanner = null;
  62153. }
  62154. if (this._soundSource) {
  62155. this._soundSource.disconnect();
  62156. this._soundSource = null;
  62157. }
  62158. this._audioBuffer = null;
  62159. if (this._htmlAudioElement) {
  62160. this._htmlAudioElement.pause();
  62161. this._htmlAudioElement.src = "";
  62162. document.body.removeChild(this._htmlAudioElement);
  62163. }
  62164. if (this._streamingSource) {
  62165. this._streamingSource.disconnect();
  62166. }
  62167. if (this._connectedMesh && this._registerFunc) {
  62168. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62169. this._connectedMesh = null;
  62170. }
  62171. }
  62172. };
  62173. Sound.prototype.isReady = function () {
  62174. return this._isReadyToPlay;
  62175. };
  62176. Sound.prototype._soundLoaded = function (audioData) {
  62177. var _this = this;
  62178. if (!BABYLON.Engine.audioEngine.audioContext) {
  62179. return;
  62180. }
  62181. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62182. _this._audioBuffer = buffer;
  62183. _this._isReadyToPlay = true;
  62184. if (_this.autoplay) {
  62185. _this.play();
  62186. }
  62187. if (_this._readyToPlayCallback) {
  62188. _this._readyToPlayCallback();
  62189. }
  62190. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62191. };
  62192. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62193. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62194. this._audioBuffer = audioBuffer;
  62195. this._isReadyToPlay = true;
  62196. }
  62197. };
  62198. Sound.prototype.updateOptions = function (options) {
  62199. if (options) {
  62200. this.loop = options.loop || this.loop;
  62201. this.maxDistance = options.maxDistance || this.maxDistance;
  62202. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62203. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62204. this.refDistance = options.refDistance || this.refDistance;
  62205. this.distanceModel = options.distanceModel || this.distanceModel;
  62206. this._playbackRate = options.playbackRate || this._playbackRate;
  62207. this._updateSpatialParameters();
  62208. if (this.isPlaying) {
  62209. if (this._streaming && this._htmlAudioElement) {
  62210. this._htmlAudioElement.playbackRate = this._playbackRate;
  62211. }
  62212. else {
  62213. if (this._soundSource) {
  62214. this._soundSource.playbackRate.value = this._playbackRate;
  62215. }
  62216. }
  62217. }
  62218. }
  62219. };
  62220. Sound.prototype._createSpatialParameters = function () {
  62221. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62222. if (this._scene.headphone) {
  62223. this._panningModel = "HRTF";
  62224. }
  62225. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62226. this._updateSpatialParameters();
  62227. this._soundPanner.connect(this._ouputAudioNode);
  62228. this._inputAudioNode = this._soundPanner;
  62229. }
  62230. };
  62231. Sound.prototype._updateSpatialParameters = function () {
  62232. if (this.spatialSound && this._soundPanner) {
  62233. if (this.useCustomAttenuation) {
  62234. // Tricks to disable in a way embedded Web Audio attenuation
  62235. this._soundPanner.distanceModel = "linear";
  62236. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62237. this._soundPanner.refDistance = 1;
  62238. this._soundPanner.rolloffFactor = 1;
  62239. this._soundPanner.panningModel = this._panningModel;
  62240. }
  62241. else {
  62242. this._soundPanner.distanceModel = this.distanceModel;
  62243. this._soundPanner.maxDistance = this.maxDistance;
  62244. this._soundPanner.refDistance = this.refDistance;
  62245. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62246. this._soundPanner.panningModel = this._panningModel;
  62247. }
  62248. }
  62249. };
  62250. Sound.prototype.switchPanningModelToHRTF = function () {
  62251. this._panningModel = "HRTF";
  62252. this._switchPanningModel();
  62253. };
  62254. Sound.prototype.switchPanningModelToEqualPower = function () {
  62255. this._panningModel = "equalpower";
  62256. this._switchPanningModel();
  62257. };
  62258. Sound.prototype._switchPanningModel = function () {
  62259. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62260. this._soundPanner.panningModel = this._panningModel;
  62261. }
  62262. };
  62263. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62264. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62265. if (this._isOutputConnected) {
  62266. this._ouputAudioNode.disconnect();
  62267. }
  62268. this._ouputAudioNode.connect(soundTrackAudioNode);
  62269. this._isOutputConnected = true;
  62270. }
  62271. };
  62272. /**
  62273. * Transform this sound into a directional source
  62274. * @param coneInnerAngle Size of the inner cone in degree
  62275. * @param coneOuterAngle Size of the outer cone in degree
  62276. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62277. */
  62278. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62279. if (coneOuterAngle < coneInnerAngle) {
  62280. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62281. return;
  62282. }
  62283. this._coneInnerAngle = coneInnerAngle;
  62284. this._coneOuterAngle = coneOuterAngle;
  62285. this._coneOuterGain = coneOuterGain;
  62286. this._isDirectional = true;
  62287. if (this.isPlaying && this.loop) {
  62288. this.stop();
  62289. this.play();
  62290. }
  62291. };
  62292. Sound.prototype.setPosition = function (newPosition) {
  62293. this._position = newPosition;
  62294. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62295. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62296. }
  62297. };
  62298. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62299. this._localDirection = newLocalDirection;
  62300. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62301. this._updateDirection();
  62302. }
  62303. };
  62304. Sound.prototype._updateDirection = function () {
  62305. if (!this._connectedMesh || !this._soundPanner) {
  62306. return;
  62307. }
  62308. var mat = this._connectedMesh.getWorldMatrix();
  62309. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62310. direction.normalize();
  62311. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62312. };
  62313. Sound.prototype.updateDistanceFromListener = function () {
  62314. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62315. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62316. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62317. }
  62318. };
  62319. Sound.prototype.setAttenuationFunction = function (callback) {
  62320. this._customAttenuationFunction = callback;
  62321. };
  62322. /**
  62323. * Play the sound
  62324. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62325. * @param offset (optional) Start the sound setting it at a specific time
  62326. */
  62327. Sound.prototype.play = function (time, offset) {
  62328. var _this = this;
  62329. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62330. try {
  62331. if (this._startOffset < 0) {
  62332. time = -this._startOffset;
  62333. this._startOffset = 0;
  62334. }
  62335. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62336. if (!this._soundSource || !this._streamingSource) {
  62337. if (this.spatialSound && this._soundPanner) {
  62338. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62339. if (this._isDirectional) {
  62340. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62341. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62342. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62343. if (this._connectedMesh) {
  62344. this._updateDirection();
  62345. }
  62346. else {
  62347. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62348. }
  62349. }
  62350. }
  62351. }
  62352. if (this._streaming) {
  62353. if (!this._streamingSource) {
  62354. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62355. this._htmlAudioElement.onended = function () { _this._onended(); };
  62356. this._htmlAudioElement.playbackRate = this._playbackRate;
  62357. }
  62358. this._streamingSource.disconnect();
  62359. this._streamingSource.connect(this._inputAudioNode);
  62360. if (this._htmlAudioElement) {
  62361. this._htmlAudioElement.play();
  62362. }
  62363. }
  62364. else {
  62365. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62366. this._soundSource.buffer = this._audioBuffer;
  62367. this._soundSource.connect(this._inputAudioNode);
  62368. this._soundSource.loop = this.loop;
  62369. this._soundSource.playbackRate.value = this._playbackRate;
  62370. this._soundSource.onended = function () { _this._onended(); };
  62371. if (this._soundSource.buffer) {
  62372. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62373. }
  62374. }
  62375. this._startTime = startTime;
  62376. this.isPlaying = true;
  62377. this.isPaused = false;
  62378. }
  62379. catch (ex) {
  62380. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62381. }
  62382. }
  62383. };
  62384. Sound.prototype._onended = function () {
  62385. this.isPlaying = false;
  62386. if (this.onended) {
  62387. this.onended();
  62388. }
  62389. };
  62390. /**
  62391. * Stop the sound
  62392. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62393. */
  62394. Sound.prototype.stop = function (time) {
  62395. if (this.isPlaying) {
  62396. if (this._streaming) {
  62397. if (this._htmlAudioElement) {
  62398. this._htmlAudioElement.pause();
  62399. // Test needed for Firefox or it will generate an Invalid State Error
  62400. if (this._htmlAudioElement.currentTime > 0) {
  62401. this._htmlAudioElement.currentTime = 0;
  62402. }
  62403. }
  62404. else {
  62405. this._streamingSource.disconnect();
  62406. }
  62407. }
  62408. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62409. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62410. this._soundSource.stop(stopTime);
  62411. this._soundSource.onended = function () { };
  62412. if (!this.isPaused) {
  62413. this._startOffset = 0;
  62414. }
  62415. }
  62416. this.isPlaying = false;
  62417. }
  62418. };
  62419. Sound.prototype.pause = function () {
  62420. if (this.isPlaying) {
  62421. this.isPaused = true;
  62422. if (this._streaming) {
  62423. if (this._htmlAudioElement) {
  62424. this._htmlAudioElement.pause();
  62425. }
  62426. else {
  62427. this._streamingSource.disconnect();
  62428. }
  62429. }
  62430. else if (BABYLON.Engine.audioEngine.audioContext) {
  62431. this.stop(0);
  62432. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62433. }
  62434. }
  62435. };
  62436. Sound.prototype.setVolume = function (newVolume, time) {
  62437. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62438. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62439. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62440. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62441. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62442. }
  62443. else {
  62444. this._soundGain.gain.value = newVolume;
  62445. }
  62446. }
  62447. this._volume = newVolume;
  62448. };
  62449. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62450. this._playbackRate = newPlaybackRate;
  62451. if (this.isPlaying) {
  62452. if (this._streaming && this._htmlAudioElement) {
  62453. this._htmlAudioElement.playbackRate = this._playbackRate;
  62454. }
  62455. else if (this._soundSource) {
  62456. this._soundSource.playbackRate.value = this._playbackRate;
  62457. }
  62458. }
  62459. };
  62460. Sound.prototype.getVolume = function () {
  62461. return this._volume;
  62462. };
  62463. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62464. var _this = this;
  62465. if (this._connectedMesh && this._registerFunc) {
  62466. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62467. this._registerFunc = null;
  62468. }
  62469. this._connectedMesh = meshToConnectTo;
  62470. if (!this.spatialSound) {
  62471. this.spatialSound = true;
  62472. this._createSpatialParameters();
  62473. if (this.isPlaying && this.loop) {
  62474. this.stop();
  62475. this.play();
  62476. }
  62477. }
  62478. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62479. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62480. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62481. };
  62482. Sound.prototype.detachFromMesh = function () {
  62483. if (this._connectedMesh && this._registerFunc) {
  62484. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62485. this._registerFunc = null;
  62486. this._connectedMesh = null;
  62487. }
  62488. };
  62489. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62490. if (!node.getBoundingInfo) {
  62491. return;
  62492. }
  62493. var mesh = node;
  62494. var boundingInfo = mesh.getBoundingInfo();
  62495. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62496. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62497. this._updateDirection();
  62498. }
  62499. };
  62500. Sound.prototype.clone = function () {
  62501. var _this = this;
  62502. if (!this._streaming) {
  62503. var setBufferAndRun = function () {
  62504. if (_this._isReadyToPlay) {
  62505. clonedSound._audioBuffer = _this.getAudioBuffer();
  62506. clonedSound._isReadyToPlay = true;
  62507. if (clonedSound.autoplay) {
  62508. clonedSound.play();
  62509. }
  62510. }
  62511. else {
  62512. window.setTimeout(setBufferAndRun, 300);
  62513. }
  62514. };
  62515. var currentOptions = {
  62516. autoplay: this.autoplay, loop: this.loop,
  62517. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62518. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62519. refDistance: this.refDistance, distanceModel: this.distanceModel
  62520. };
  62521. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62522. if (this.useCustomAttenuation) {
  62523. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62524. }
  62525. clonedSound.setPosition(this._position);
  62526. clonedSound.setPlaybackRate(this._playbackRate);
  62527. setBufferAndRun();
  62528. return clonedSound;
  62529. }
  62530. // Can't clone a streaming sound
  62531. else {
  62532. return null;
  62533. }
  62534. };
  62535. Sound.prototype.getAudioBuffer = function () {
  62536. return this._audioBuffer;
  62537. };
  62538. Sound.prototype.serialize = function () {
  62539. var serializationObject = {
  62540. name: this.name,
  62541. url: this.name,
  62542. autoplay: this.autoplay,
  62543. loop: this.loop,
  62544. volume: this._volume,
  62545. spatialSound: this.spatialSound,
  62546. maxDistance: this.maxDistance,
  62547. rolloffFactor: this.rolloffFactor,
  62548. refDistance: this.refDistance,
  62549. distanceModel: this.distanceModel,
  62550. playbackRate: this._playbackRate,
  62551. panningModel: this._panningModel,
  62552. soundTrackId: this.soundTrackId
  62553. };
  62554. if (this.spatialSound) {
  62555. if (this._connectedMesh)
  62556. serializationObject.connectedMeshId = this._connectedMesh.id;
  62557. serializationObject.position = this._position.asArray();
  62558. serializationObject.refDistance = this.refDistance;
  62559. serializationObject.distanceModel = this.distanceModel;
  62560. serializationObject.isDirectional = this._isDirectional;
  62561. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62562. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62563. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62564. serializationObject.coneOuterGain = this._coneOuterGain;
  62565. }
  62566. return serializationObject;
  62567. };
  62568. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62569. var soundName = parsedSound.name;
  62570. var soundUrl;
  62571. if (parsedSound.url) {
  62572. soundUrl = rootUrl + parsedSound.url;
  62573. }
  62574. else {
  62575. soundUrl = rootUrl + soundName;
  62576. }
  62577. var options = {
  62578. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62579. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62580. rolloffFactor: parsedSound.rolloffFactor,
  62581. refDistance: parsedSound.refDistance,
  62582. distanceModel: parsedSound.distanceModel,
  62583. playbackRate: parsedSound.playbackRate
  62584. };
  62585. var newSound;
  62586. if (!sourceSound) {
  62587. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62588. scene._addPendingData(newSound);
  62589. }
  62590. else {
  62591. var setBufferAndRun = function () {
  62592. if (sourceSound._isReadyToPlay) {
  62593. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62594. newSound._isReadyToPlay = true;
  62595. if (newSound.autoplay) {
  62596. newSound.play();
  62597. }
  62598. }
  62599. else {
  62600. window.setTimeout(setBufferAndRun, 300);
  62601. }
  62602. };
  62603. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62604. setBufferAndRun();
  62605. }
  62606. if (parsedSound.position) {
  62607. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62608. newSound.setPosition(soundPosition);
  62609. }
  62610. if (parsedSound.isDirectional) {
  62611. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62612. if (parsedSound.localDirectionToMesh) {
  62613. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62614. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62615. }
  62616. }
  62617. if (parsedSound.connectedMeshId) {
  62618. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62619. if (connectedMesh) {
  62620. newSound.attachToMesh(connectedMesh);
  62621. }
  62622. }
  62623. return newSound;
  62624. };
  62625. return Sound;
  62626. }());
  62627. BABYLON.Sound = Sound;
  62628. })(BABYLON || (BABYLON = {}));
  62629. //# sourceMappingURL=babylon.sound.js.map
  62630. var BABYLON;
  62631. (function (BABYLON) {
  62632. var SoundTrack = /** @class */ (function () {
  62633. function SoundTrack(scene, options) {
  62634. this.id = -1;
  62635. this._isMainTrack = false;
  62636. this._isInitialized = false;
  62637. this._scene = scene;
  62638. this.soundCollection = new Array();
  62639. this._options = options;
  62640. if (!this._isMainTrack) {
  62641. this._scene.soundTracks.push(this);
  62642. this.id = this._scene.soundTracks.length - 1;
  62643. }
  62644. }
  62645. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62646. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62647. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62648. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62649. if (this._options) {
  62650. if (this._options.volume) {
  62651. this._outputAudioNode.gain.value = this._options.volume;
  62652. }
  62653. if (this._options.mainTrack) {
  62654. this._isMainTrack = this._options.mainTrack;
  62655. }
  62656. }
  62657. this._isInitialized = true;
  62658. }
  62659. };
  62660. SoundTrack.prototype.dispose = function () {
  62661. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62662. if (this._connectedAnalyser) {
  62663. this._connectedAnalyser.stopDebugCanvas();
  62664. }
  62665. while (this.soundCollection.length) {
  62666. this.soundCollection[0].dispose();
  62667. }
  62668. if (this._outputAudioNode) {
  62669. this._outputAudioNode.disconnect();
  62670. }
  62671. this._outputAudioNode = null;
  62672. }
  62673. };
  62674. SoundTrack.prototype.AddSound = function (sound) {
  62675. if (!this._isInitialized) {
  62676. this._initializeSoundTrackAudioGraph();
  62677. }
  62678. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62679. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62680. }
  62681. if (sound.soundTrackId) {
  62682. if (sound.soundTrackId === -1) {
  62683. this._scene.mainSoundTrack.RemoveSound(sound);
  62684. }
  62685. else {
  62686. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62687. }
  62688. }
  62689. this.soundCollection.push(sound);
  62690. sound.soundTrackId = this.id;
  62691. };
  62692. SoundTrack.prototype.RemoveSound = function (sound) {
  62693. var index = this.soundCollection.indexOf(sound);
  62694. if (index !== -1) {
  62695. this.soundCollection.splice(index, 1);
  62696. }
  62697. };
  62698. SoundTrack.prototype.setVolume = function (newVolume) {
  62699. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62700. this._outputAudioNode.gain.value = newVolume;
  62701. }
  62702. };
  62703. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62704. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62705. for (var i = 0; i < this.soundCollection.length; i++) {
  62706. this.soundCollection[i].switchPanningModelToHRTF();
  62707. }
  62708. }
  62709. };
  62710. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62711. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62712. for (var i = 0; i < this.soundCollection.length; i++) {
  62713. this.soundCollection[i].switchPanningModelToEqualPower();
  62714. }
  62715. }
  62716. };
  62717. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62718. if (this._connectedAnalyser) {
  62719. this._connectedAnalyser.stopDebugCanvas();
  62720. }
  62721. this._connectedAnalyser = analyser;
  62722. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62723. this._outputAudioNode.disconnect();
  62724. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62725. }
  62726. };
  62727. return SoundTrack;
  62728. }());
  62729. BABYLON.SoundTrack = SoundTrack;
  62730. })(BABYLON || (BABYLON = {}));
  62731. //# sourceMappingURL=babylon.soundtrack.js.map
  62732. var BABYLON;
  62733. (function (BABYLON) {
  62734. /**
  62735. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62736. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62737. */
  62738. var Analyser = /** @class */ (function () {
  62739. /**
  62740. * Creates a new analyser
  62741. * @param scene defines hosting scene
  62742. */
  62743. function Analyser(scene) {
  62744. /**
  62745. * Gets or sets the smoothing
  62746. * @ignorenaming
  62747. */
  62748. this.SMOOTHING = 0.75;
  62749. /**
  62750. * Gets or sets the FFT table size
  62751. * @ignorenaming
  62752. */
  62753. this.FFT_SIZE = 512;
  62754. /**
  62755. * Gets or sets the bar graph amplitude
  62756. * @ignorenaming
  62757. */
  62758. this.BARGRAPHAMPLITUDE = 256;
  62759. /**
  62760. * Gets or sets the position of the debug canvas
  62761. * @ignorenaming
  62762. */
  62763. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62764. /**
  62765. * Gets or sets the debug canvas size
  62766. * @ignorenaming
  62767. */
  62768. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62769. this._scene = scene;
  62770. this._audioEngine = BABYLON.Engine.audioEngine;
  62771. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62772. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62773. this._webAudioAnalyser.minDecibels = -140;
  62774. this._webAudioAnalyser.maxDecibels = 0;
  62775. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62776. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62777. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62778. }
  62779. }
  62780. /**
  62781. * Get the number of data values you will have to play with for the visualization
  62782. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62783. * @returns a number
  62784. */
  62785. Analyser.prototype.getFrequencyBinCount = function () {
  62786. if (this._audioEngine.canUseWebAudio) {
  62787. return this._webAudioAnalyser.frequencyBinCount;
  62788. }
  62789. else {
  62790. return 0;
  62791. }
  62792. };
  62793. /**
  62794. * Gets the current frequency data as a byte array
  62795. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62796. * @returns a Uint8Array
  62797. */
  62798. Analyser.prototype.getByteFrequencyData = function () {
  62799. if (this._audioEngine.canUseWebAudio) {
  62800. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62801. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62802. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62803. }
  62804. return this._byteFreqs;
  62805. };
  62806. /**
  62807. * Gets the current waveform as a byte array
  62808. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62809. * @returns a Uint8Array
  62810. */
  62811. Analyser.prototype.getByteTimeDomainData = function () {
  62812. if (this._audioEngine.canUseWebAudio) {
  62813. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62814. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62815. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62816. }
  62817. return this._byteTime;
  62818. };
  62819. /**
  62820. * Gets the current frequency data as a float array
  62821. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62822. * @returns a Float32Array
  62823. */
  62824. Analyser.prototype.getFloatFrequencyData = function () {
  62825. if (this._audioEngine.canUseWebAudio) {
  62826. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62827. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62828. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62829. }
  62830. return this._floatFreqs;
  62831. };
  62832. /**
  62833. * Renders the debug canvas
  62834. */
  62835. Analyser.prototype.drawDebugCanvas = function () {
  62836. var _this = this;
  62837. if (this._audioEngine.canUseWebAudio) {
  62838. if (!this._debugCanvas) {
  62839. this._debugCanvas = document.createElement("canvas");
  62840. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62841. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62842. this._debugCanvas.style.position = "absolute";
  62843. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62844. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62845. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62846. document.body.appendChild(this._debugCanvas);
  62847. this._registerFunc = function () {
  62848. _this.drawDebugCanvas();
  62849. };
  62850. this._scene.registerBeforeRender(this._registerFunc);
  62851. }
  62852. if (this._registerFunc && this._debugCanvasContext) {
  62853. var workingArray = this.getByteFrequencyData();
  62854. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62855. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62856. // Draw the frequency domain chart.
  62857. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62858. var value = workingArray[i];
  62859. var percent = value / this.BARGRAPHAMPLITUDE;
  62860. var height = this.DEBUGCANVASSIZE.height * percent;
  62861. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62862. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62863. var hue = i / this.getFrequencyBinCount() * 360;
  62864. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62865. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62866. }
  62867. }
  62868. }
  62869. };
  62870. /**
  62871. * Stops rendering the debug canvas and removes it
  62872. */
  62873. Analyser.prototype.stopDebugCanvas = function () {
  62874. if (this._debugCanvas) {
  62875. if (this._registerFunc) {
  62876. this._scene.unregisterBeforeRender(this._registerFunc);
  62877. this._registerFunc = null;
  62878. }
  62879. document.body.removeChild(this._debugCanvas);
  62880. this._debugCanvas = null;
  62881. this._debugCanvasContext = null;
  62882. }
  62883. };
  62884. /**
  62885. * Connects two audio nodes
  62886. * @param inputAudioNode defines first node to connect
  62887. * @param outputAudioNode defines second node to connect
  62888. */
  62889. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62890. if (this._audioEngine.canUseWebAudio) {
  62891. inputAudioNode.connect(this._webAudioAnalyser);
  62892. this._webAudioAnalyser.connect(outputAudioNode);
  62893. }
  62894. };
  62895. /**
  62896. * Releases all associated resources
  62897. */
  62898. Analyser.prototype.dispose = function () {
  62899. if (this._audioEngine.canUseWebAudio) {
  62900. this._webAudioAnalyser.disconnect();
  62901. }
  62902. };
  62903. return Analyser;
  62904. }());
  62905. BABYLON.Analyser = Analyser;
  62906. })(BABYLON || (BABYLON = {}));
  62907. //# sourceMappingURL=babylon.analyser.js.map
  62908. var BABYLON;
  62909. (function (BABYLON) {
  62910. var CubeTexture = /** @class */ (function (_super) {
  62911. __extends(CubeTexture, _super);
  62912. /**
  62913. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  62914. * as prefiltered data.
  62915. * @param rootUrl defines the url of the texture or the root name of the six images
  62916. * @param scene defines the scene the texture is attached to
  62917. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  62918. * @param noMipmap defines if mipmaps should be created or not
  62919. * @param files defines the six files to load for the different faces
  62920. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  62921. * @param onError defines a callback triggered in case of error during load
  62922. * @param format defines the internal format to use for the texture once loaded
  62923. * @param prefiltered defines whether or not the texture is created from prefiltered data
  62924. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  62925. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  62926. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  62927. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  62928. * @return the cube texture
  62929. */
  62930. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  62931. if (extensions === void 0) { extensions = null; }
  62932. if (noMipmap === void 0) { noMipmap = false; }
  62933. if (files === void 0) { files = null; }
  62934. if (onLoad === void 0) { onLoad = null; }
  62935. if (onError === void 0) { onError = null; }
  62936. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62937. if (prefiltered === void 0) { prefiltered = false; }
  62938. if (forcedExtension === void 0) { forcedExtension = null; }
  62939. if (createPolynomials === void 0) { createPolynomials = false; }
  62940. if (lodScale === void 0) { lodScale = 0.8; }
  62941. if (lodOffset === void 0) { lodOffset = 0; }
  62942. var _this = _super.call(this, scene) || this;
  62943. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62944. /**
  62945. * Gets or sets the center of the bounding box associated with the cube texture
  62946. * It must define where the camera used to render the texture was set
  62947. */
  62948. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62949. _this._rotationY = 0;
  62950. /** @hidden */
  62951. _this._prefiltered = false;
  62952. _this.name = rootUrl;
  62953. _this.url = rootUrl;
  62954. _this._noMipmap = noMipmap;
  62955. _this.hasAlpha = false;
  62956. _this._format = format;
  62957. _this.isCube = true;
  62958. _this._textureMatrix = BABYLON.Matrix.Identity();
  62959. _this._createPolynomials = createPolynomials;
  62960. if (!rootUrl && !files) {
  62961. return _this;
  62962. }
  62963. var lastDot = rootUrl.lastIndexOf(".");
  62964. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  62965. var isDDS = (extension === ".dds");
  62966. var isEnv = (extension === ".env");
  62967. if (isEnv) {
  62968. _this.gammaSpace = false;
  62969. _this._prefiltered = false;
  62970. }
  62971. else {
  62972. _this._prefiltered = prefiltered;
  62973. if (prefiltered) {
  62974. _this.gammaSpace = false;
  62975. }
  62976. }
  62977. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  62978. if (!files) {
  62979. if (!isEnv && !isDDS && !extensions) {
  62980. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  62981. }
  62982. files = [];
  62983. if (extensions) {
  62984. for (var index = 0; index < extensions.length; index++) {
  62985. files.push(rootUrl + extensions[index]);
  62986. }
  62987. }
  62988. }
  62989. _this._files = files;
  62990. if (!_this._texture) {
  62991. if (!scene.useDelayedTextureLoading) {
  62992. if (prefiltered) {
  62993. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  62994. }
  62995. else {
  62996. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  62997. }
  62998. }
  62999. else {
  63000. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63001. }
  63002. }
  63003. else if (onLoad) {
  63004. if (_this._texture.isReady) {
  63005. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63006. }
  63007. else {
  63008. _this._texture.onLoadedObservable.add(onLoad);
  63009. }
  63010. }
  63011. return _this;
  63012. }
  63013. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63014. get: function () {
  63015. return this._boundingBoxSize;
  63016. },
  63017. /**
  63018. * Gets or sets the size of the bounding box associated with the cube texture
  63019. * When defined, the cubemap will switch to local mode
  63020. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63021. * @example https://www.babylonjs-playground.com/#RNASML
  63022. */
  63023. set: function (value) {
  63024. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63025. return;
  63026. }
  63027. this._boundingBoxSize = value;
  63028. var scene = this.getScene();
  63029. if (scene) {
  63030. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63031. }
  63032. },
  63033. enumerable: true,
  63034. configurable: true
  63035. });
  63036. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63037. /**
  63038. * Gets texture matrix rotation angle around Y axis radians.
  63039. */
  63040. get: function () {
  63041. return this._rotationY;
  63042. },
  63043. /**
  63044. * Sets texture matrix rotation angle around Y axis in radians.
  63045. */
  63046. set: function (value) {
  63047. this._rotationY = value;
  63048. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63049. },
  63050. enumerable: true,
  63051. configurable: true
  63052. });
  63053. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63054. var rootUrlKey = "";
  63055. files.forEach(function (url) { return rootUrlKey += url; });
  63056. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63057. };
  63058. /**
  63059. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63060. * @param url defines the url of the prefiltered texture
  63061. * @param scene defines the scene the texture is attached to
  63062. * @param forcedExtension defines the extension of the file if different from the url
  63063. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63064. * @return the prefiltered texture
  63065. */
  63066. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63067. if (forcedExtension === void 0) { forcedExtension = null; }
  63068. if (createPolynomials === void 0) { createPolynomials = true; }
  63069. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63070. };
  63071. // Methods
  63072. CubeTexture.prototype.delayLoad = function () {
  63073. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63074. return;
  63075. }
  63076. var scene = this.getScene();
  63077. if (!scene) {
  63078. return;
  63079. }
  63080. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63081. this._texture = this._getFromCache(this.url, this._noMipmap);
  63082. if (!this._texture) {
  63083. if (this._prefiltered) {
  63084. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63085. }
  63086. else {
  63087. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63088. }
  63089. }
  63090. };
  63091. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63092. return this._textureMatrix;
  63093. };
  63094. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63095. this._textureMatrix = value;
  63096. };
  63097. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63098. var texture = BABYLON.SerializationHelper.Parse(function () {
  63099. var prefiltered = false;
  63100. if (parsedTexture.prefiltered) {
  63101. prefiltered = parsedTexture.prefiltered;
  63102. }
  63103. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63104. }, parsedTexture, scene);
  63105. // Local Cubemaps
  63106. if (parsedTexture.boundingBoxPosition) {
  63107. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63108. }
  63109. if (parsedTexture.boundingBoxSize) {
  63110. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63111. }
  63112. // Animations
  63113. if (parsedTexture.animations) {
  63114. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63115. var parsedAnimation = parsedTexture.animations[animationIndex];
  63116. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63117. }
  63118. }
  63119. return texture;
  63120. };
  63121. CubeTexture.prototype.clone = function () {
  63122. var _this = this;
  63123. return BABYLON.SerializationHelper.Clone(function () {
  63124. var scene = _this.getScene();
  63125. if (!scene) {
  63126. return _this;
  63127. }
  63128. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63129. }, this);
  63130. };
  63131. __decorate([
  63132. BABYLON.serialize("rotationY")
  63133. ], CubeTexture.prototype, "_rotationY", void 0);
  63134. return CubeTexture;
  63135. }(BABYLON.BaseTexture));
  63136. BABYLON.CubeTexture = CubeTexture;
  63137. })(BABYLON || (BABYLON = {}));
  63138. //# sourceMappingURL=babylon.cubeTexture.js.map
  63139. var BABYLON;
  63140. (function (BABYLON) {
  63141. var RenderTargetTexture = /** @class */ (function (_super) {
  63142. __extends(RenderTargetTexture, _super);
  63143. /**
  63144. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63145. * or used a shadow, depth texture...
  63146. * @param name The friendly name of the texture
  63147. * @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)
  63148. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63149. * @param generateMipMaps True if mip maps need to be generated after render.
  63150. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63151. * @param type The type of the buffer in the RTT (int, half float, float...)
  63152. * @param isCube True if a cube texture needs to be created
  63153. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63154. * @param generateDepthBuffer True to generate a depth buffer
  63155. * @param generateStencilBuffer True to generate a stencil buffer
  63156. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63157. */
  63158. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63159. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63160. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63161. if (isCube === void 0) { isCube = false; }
  63162. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63163. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63164. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63165. if (isMulti === void 0) { isMulti = false; }
  63166. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63167. _this.isCube = isCube;
  63168. /**
  63169. * Use this list to define the list of mesh you want to render.
  63170. */
  63171. _this.renderList = new Array();
  63172. _this.renderParticles = true;
  63173. _this.renderSprites = false;
  63174. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63175. _this.ignoreCameraViewport = false;
  63176. // Events
  63177. /**
  63178. * An event triggered when the texture is unbind.
  63179. */
  63180. _this.onBeforeBindObservable = new BABYLON.Observable();
  63181. /**
  63182. * An event triggered when the texture is unbind.
  63183. */
  63184. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63185. /**
  63186. * An event triggered before rendering the texture
  63187. */
  63188. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63189. /**
  63190. * An event triggered after rendering the texture
  63191. */
  63192. _this.onAfterRenderObservable = new BABYLON.Observable();
  63193. /**
  63194. * An event triggered after the texture clear
  63195. */
  63196. _this.onClearObservable = new BABYLON.Observable();
  63197. _this._currentRefreshId = -1;
  63198. _this._refreshRate = 1;
  63199. _this._samples = 1;
  63200. /**
  63201. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63202. * It must define where the camera used to render the texture is set
  63203. */
  63204. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63205. scene = _this.getScene();
  63206. if (!scene) {
  63207. return _this;
  63208. }
  63209. _this._engine = scene.getEngine();
  63210. _this.name = name;
  63211. _this.isRenderTarget = true;
  63212. _this._initialSizeParameter = size;
  63213. _this._processSizeParameter(size);
  63214. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63215. });
  63216. _this._generateMipMaps = generateMipMaps ? true : false;
  63217. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63218. // Rendering groups
  63219. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63220. if (isMulti) {
  63221. return _this;
  63222. }
  63223. _this._renderTargetOptions = {
  63224. generateMipMaps: generateMipMaps,
  63225. type: type,
  63226. samplingMode: samplingMode,
  63227. generateDepthBuffer: generateDepthBuffer,
  63228. generateStencilBuffer: generateStencilBuffer
  63229. };
  63230. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63231. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63232. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63233. }
  63234. if (isCube) {
  63235. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63236. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63237. _this._textureMatrix = BABYLON.Matrix.Identity();
  63238. }
  63239. else {
  63240. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63241. }
  63242. return _this;
  63243. }
  63244. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63245. get: function () {
  63246. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63247. },
  63248. enumerable: true,
  63249. configurable: true
  63250. });
  63251. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63252. get: function () {
  63253. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63254. },
  63255. enumerable: true,
  63256. configurable: true
  63257. });
  63258. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63259. get: function () {
  63260. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63261. },
  63262. enumerable: true,
  63263. configurable: true
  63264. });
  63265. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63266. set: function (callback) {
  63267. if (this._onAfterUnbindObserver) {
  63268. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63269. }
  63270. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63271. },
  63272. enumerable: true,
  63273. configurable: true
  63274. });
  63275. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63276. set: function (callback) {
  63277. if (this._onBeforeRenderObserver) {
  63278. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63279. }
  63280. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63281. },
  63282. enumerable: true,
  63283. configurable: true
  63284. });
  63285. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63286. set: function (callback) {
  63287. if (this._onAfterRenderObserver) {
  63288. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63289. }
  63290. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63291. },
  63292. enumerable: true,
  63293. configurable: true
  63294. });
  63295. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63296. set: function (callback) {
  63297. if (this._onClearObserver) {
  63298. this.onClearObservable.remove(this._onClearObserver);
  63299. }
  63300. this._onClearObserver = this.onClearObservable.add(callback);
  63301. },
  63302. enumerable: true,
  63303. configurable: true
  63304. });
  63305. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63306. get: function () {
  63307. return this._renderTargetOptions;
  63308. },
  63309. enumerable: true,
  63310. configurable: true
  63311. });
  63312. RenderTargetTexture.prototype._onRatioRescale = function () {
  63313. if (this._sizeRatio) {
  63314. this.resize(this._initialSizeParameter);
  63315. }
  63316. };
  63317. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63318. get: function () {
  63319. return this._boundingBoxSize;
  63320. },
  63321. /**
  63322. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63323. * When defined, the cubemap will switch to local mode
  63324. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63325. * @example https://www.babylonjs-playground.com/#RNASML
  63326. */
  63327. set: function (value) {
  63328. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63329. return;
  63330. }
  63331. this._boundingBoxSize = value;
  63332. var scene = this.getScene();
  63333. if (scene) {
  63334. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63335. }
  63336. },
  63337. enumerable: true,
  63338. configurable: true
  63339. });
  63340. /**
  63341. * Creates a depth stencil texture.
  63342. * This is only available in WebGL 2 or with the depth texture extension available.
  63343. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63344. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63345. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63346. */
  63347. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63348. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63349. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63350. if (generateStencil === void 0) { generateStencil = false; }
  63351. if (!this.getScene()) {
  63352. return;
  63353. }
  63354. var engine = this.getScene().getEngine();
  63355. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63356. bilinearFiltering: bilinearFiltering,
  63357. comparisonFunction: comparisonFunction,
  63358. generateStencil: generateStencil,
  63359. isCube: this.isCube
  63360. });
  63361. engine.setFrameBufferDepthStencilTexture(this);
  63362. };
  63363. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63364. if (size.ratio) {
  63365. this._sizeRatio = size.ratio;
  63366. this._size = {
  63367. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63368. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63369. };
  63370. }
  63371. else {
  63372. this._size = size;
  63373. }
  63374. };
  63375. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63376. get: function () {
  63377. return this._samples;
  63378. },
  63379. set: function (value) {
  63380. if (this._samples === value) {
  63381. return;
  63382. }
  63383. var scene = this.getScene();
  63384. if (!scene) {
  63385. return;
  63386. }
  63387. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63388. },
  63389. enumerable: true,
  63390. configurable: true
  63391. });
  63392. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63393. this._currentRefreshId = -1;
  63394. };
  63395. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63396. get: function () {
  63397. return this._refreshRate;
  63398. },
  63399. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63400. set: function (value) {
  63401. this._refreshRate = value;
  63402. this.resetRefreshCounter();
  63403. },
  63404. enumerable: true,
  63405. configurable: true
  63406. });
  63407. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63408. if (!this._postProcessManager) {
  63409. var scene = this.getScene();
  63410. if (!scene) {
  63411. return;
  63412. }
  63413. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63414. this._postProcesses = new Array();
  63415. }
  63416. this._postProcesses.push(postProcess);
  63417. this._postProcesses[0].autoClear = false;
  63418. };
  63419. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63420. if (!this._postProcesses) {
  63421. return;
  63422. }
  63423. if (dispose) {
  63424. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63425. var postProcess = _a[_i];
  63426. postProcess.dispose();
  63427. }
  63428. }
  63429. this._postProcesses = [];
  63430. };
  63431. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63432. if (!this._postProcesses) {
  63433. return;
  63434. }
  63435. var index = this._postProcesses.indexOf(postProcess);
  63436. if (index === -1) {
  63437. return;
  63438. }
  63439. this._postProcesses.splice(index, 1);
  63440. if (this._postProcesses.length > 0) {
  63441. this._postProcesses[0].autoClear = false;
  63442. }
  63443. };
  63444. RenderTargetTexture.prototype._shouldRender = function () {
  63445. if (this._currentRefreshId === -1) { // At least render once
  63446. this._currentRefreshId = 1;
  63447. return true;
  63448. }
  63449. if (this.refreshRate === this._currentRefreshId) {
  63450. this._currentRefreshId = 1;
  63451. return true;
  63452. }
  63453. this._currentRefreshId++;
  63454. return false;
  63455. };
  63456. RenderTargetTexture.prototype.getRenderSize = function () {
  63457. if (this._size.width) {
  63458. return this._size.width;
  63459. }
  63460. return this._size;
  63461. };
  63462. RenderTargetTexture.prototype.getRenderWidth = function () {
  63463. if (this._size.width) {
  63464. return this._size.width;
  63465. }
  63466. return this._size;
  63467. };
  63468. RenderTargetTexture.prototype.getRenderHeight = function () {
  63469. if (this._size.width) {
  63470. return this._size.height;
  63471. }
  63472. return this._size;
  63473. };
  63474. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63475. get: function () {
  63476. return true;
  63477. },
  63478. enumerable: true,
  63479. configurable: true
  63480. });
  63481. RenderTargetTexture.prototype.scale = function (ratio) {
  63482. var newSize = this.getRenderSize() * ratio;
  63483. this.resize(newSize);
  63484. };
  63485. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63486. if (this.isCube) {
  63487. return this._textureMatrix;
  63488. }
  63489. return _super.prototype.getReflectionTextureMatrix.call(this);
  63490. };
  63491. RenderTargetTexture.prototype.resize = function (size) {
  63492. this.releaseInternalTexture();
  63493. var scene = this.getScene();
  63494. if (!scene) {
  63495. return;
  63496. }
  63497. this._processSizeParameter(size);
  63498. if (this.isCube) {
  63499. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63500. }
  63501. else {
  63502. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63503. }
  63504. };
  63505. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63506. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63507. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63508. var scene = this.getScene();
  63509. if (!scene) {
  63510. return;
  63511. }
  63512. var engine = scene.getEngine();
  63513. if (this.useCameraPostProcesses !== undefined) {
  63514. useCameraPostProcess = this.useCameraPostProcesses;
  63515. }
  63516. if (this._waitingRenderList) {
  63517. this.renderList = [];
  63518. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63519. var id = this._waitingRenderList[index];
  63520. var mesh_1 = scene.getMeshByID(id);
  63521. if (mesh_1) {
  63522. this.renderList.push(mesh_1);
  63523. }
  63524. }
  63525. delete this._waitingRenderList;
  63526. }
  63527. // Is predicate defined?
  63528. if (this.renderListPredicate) {
  63529. if (this.renderList) {
  63530. this.renderList.splice(0); // Clear previous renderList
  63531. }
  63532. else {
  63533. this.renderList = [];
  63534. }
  63535. var scene = this.getScene();
  63536. if (!scene) {
  63537. return;
  63538. }
  63539. var sceneMeshes = scene.meshes;
  63540. for (var index = 0; index < sceneMeshes.length; index++) {
  63541. var mesh = sceneMeshes[index];
  63542. if (this.renderListPredicate(mesh)) {
  63543. this.renderList.push(mesh);
  63544. }
  63545. }
  63546. }
  63547. this.onBeforeBindObservable.notifyObservers(this);
  63548. // Set custom projection.
  63549. // Needs to be before binding to prevent changing the aspect ratio.
  63550. var camera;
  63551. if (this.activeCamera) {
  63552. camera = this.activeCamera;
  63553. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63554. if (this.activeCamera !== scene.activeCamera) {
  63555. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63556. }
  63557. }
  63558. else {
  63559. camera = scene.activeCamera;
  63560. if (camera) {
  63561. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63562. }
  63563. }
  63564. // Prepare renderingManager
  63565. this._renderingManager.reset();
  63566. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63567. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63568. var sceneRenderId = scene.getRenderId();
  63569. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63570. var mesh = currentRenderList[meshIndex];
  63571. if (mesh) {
  63572. if (!mesh.isReady(this.refreshRate === 0)) {
  63573. this.resetRefreshCounter();
  63574. continue;
  63575. }
  63576. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63577. var isMasked = void 0;
  63578. if (!this.renderList && camera) {
  63579. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63580. }
  63581. else {
  63582. isMasked = false;
  63583. }
  63584. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63585. mesh._activate(sceneRenderId);
  63586. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63587. var subMesh = mesh.subMeshes[subIndex];
  63588. scene._activeIndices.addCount(subMesh.indexCount, false);
  63589. this._renderingManager.dispatch(subMesh, mesh);
  63590. }
  63591. }
  63592. }
  63593. }
  63594. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63595. var particleSystem = scene.particleSystems[particleIndex];
  63596. var emitter = particleSystem.emitter;
  63597. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63598. continue;
  63599. }
  63600. if (currentRenderList.indexOf(emitter) >= 0) {
  63601. this._renderingManager.dispatchParticles(particleSystem);
  63602. }
  63603. }
  63604. if (this.isCube) {
  63605. for (var face = 0; face < 6; face++) {
  63606. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63607. scene.incrementRenderId();
  63608. scene.resetCachedMaterial();
  63609. }
  63610. }
  63611. else {
  63612. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63613. }
  63614. this.onAfterUnbindObservable.notifyObservers(this);
  63615. if (scene.activeCamera) {
  63616. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63617. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63618. }
  63619. engine.setViewport(scene.activeCamera.viewport);
  63620. }
  63621. scene.resetCachedMaterial();
  63622. };
  63623. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63624. var minimum = 128;
  63625. var x = renderDimension * scale;
  63626. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63627. // Ensure we don't exceed the render dimension (while staying POT)
  63628. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63629. };
  63630. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63631. var _this = this;
  63632. if (!this._texture) {
  63633. return;
  63634. }
  63635. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63636. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63637. });
  63638. };
  63639. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63640. var scene = this.getScene();
  63641. if (!scene) {
  63642. return;
  63643. }
  63644. var engine = scene.getEngine();
  63645. if (!this._texture) {
  63646. return;
  63647. }
  63648. // Bind
  63649. if (this._postProcessManager) {
  63650. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63651. }
  63652. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63653. if (this._texture) {
  63654. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63655. }
  63656. }
  63657. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63658. // Clear
  63659. if (this.onClearObservable.hasObservers()) {
  63660. this.onClearObservable.notifyObservers(engine);
  63661. }
  63662. else {
  63663. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63664. }
  63665. if (!this._doNotChangeAspectRatio) {
  63666. scene.updateTransformMatrix(true);
  63667. }
  63668. // Render
  63669. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63670. if (this._postProcessManager) {
  63671. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63672. }
  63673. else if (useCameraPostProcess) {
  63674. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63675. }
  63676. if (!this._doNotChangeAspectRatio) {
  63677. scene.updateTransformMatrix(true);
  63678. }
  63679. // Dump ?
  63680. if (dumpForDebug) {
  63681. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63682. }
  63683. // Unbind
  63684. if (!this.isCube || faceIndex === 5) {
  63685. if (this.isCube) {
  63686. if (faceIndex === 5) {
  63687. engine.generateMipMapsForCubemap(this._texture);
  63688. }
  63689. }
  63690. this.unbindFrameBuffer(engine, faceIndex);
  63691. }
  63692. else {
  63693. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63694. }
  63695. };
  63696. /**
  63697. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63698. * This allowed control for front to back rendering or reversly depending of the special needs.
  63699. *
  63700. * @param renderingGroupId The rendering group id corresponding to its index
  63701. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63702. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63703. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63704. */
  63705. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63706. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63707. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63708. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63709. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63710. };
  63711. /**
  63712. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63713. *
  63714. * @param renderingGroupId The rendering group id corresponding to its index
  63715. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63716. */
  63717. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63718. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63719. };
  63720. RenderTargetTexture.prototype.clone = function () {
  63721. var textureSize = this.getSize();
  63722. 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);
  63723. // Base texture
  63724. newTexture.hasAlpha = this.hasAlpha;
  63725. newTexture.level = this.level;
  63726. // RenderTarget Texture
  63727. newTexture.coordinatesMode = this.coordinatesMode;
  63728. if (this.renderList) {
  63729. newTexture.renderList = this.renderList.slice(0);
  63730. }
  63731. return newTexture;
  63732. };
  63733. RenderTargetTexture.prototype.serialize = function () {
  63734. if (!this.name) {
  63735. return null;
  63736. }
  63737. var serializationObject = _super.prototype.serialize.call(this);
  63738. serializationObject.renderTargetSize = this.getRenderSize();
  63739. serializationObject.renderList = [];
  63740. if (this.renderList) {
  63741. for (var index = 0; index < this.renderList.length; index++) {
  63742. serializationObject.renderList.push(this.renderList[index].id);
  63743. }
  63744. }
  63745. return serializationObject;
  63746. };
  63747. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63748. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63749. var objBuffer = this.getInternalTexture();
  63750. var scene = this.getScene();
  63751. if (objBuffer && scene) {
  63752. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63753. }
  63754. };
  63755. RenderTargetTexture.prototype.dispose = function () {
  63756. if (this._postProcessManager) {
  63757. this._postProcessManager.dispose();
  63758. this._postProcessManager = null;
  63759. }
  63760. this.clearPostProcesses(true);
  63761. if (this._resizeObserver) {
  63762. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63763. this._resizeObserver = null;
  63764. }
  63765. this.renderList = null;
  63766. // Remove from custom render targets
  63767. var scene = this.getScene();
  63768. if (!scene) {
  63769. return;
  63770. }
  63771. var index = scene.customRenderTargets.indexOf(this);
  63772. if (index >= 0) {
  63773. scene.customRenderTargets.splice(index, 1);
  63774. }
  63775. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63776. var camera = _a[_i];
  63777. index = camera.customRenderTargets.indexOf(this);
  63778. if (index >= 0) {
  63779. camera.customRenderTargets.splice(index, 1);
  63780. }
  63781. }
  63782. _super.prototype.dispose.call(this);
  63783. };
  63784. RenderTargetTexture.prototype._rebuild = function () {
  63785. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63786. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63787. }
  63788. if (this._postProcessManager) {
  63789. this._postProcessManager._rebuild();
  63790. }
  63791. };
  63792. /**
  63793. * Clear the info related to rendering groups preventing retention point in material dispose.
  63794. */
  63795. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63796. if (this._renderingManager) {
  63797. this._renderingManager.freeRenderingGroups();
  63798. }
  63799. };
  63800. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63801. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63802. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63803. return RenderTargetTexture;
  63804. }(BABYLON.Texture));
  63805. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63806. })(BABYLON || (BABYLON = {}));
  63807. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63808. var BABYLON;
  63809. (function (BABYLON) {
  63810. ;
  63811. var MultiRenderTarget = /** @class */ (function (_super) {
  63812. __extends(MultiRenderTarget, _super);
  63813. function MultiRenderTarget(name, size, count, scene, options) {
  63814. var _this = this;
  63815. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63816. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63817. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63818. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63819. _this._engine = scene.getEngine();
  63820. if (!_this.isSupported) {
  63821. _this.dispose();
  63822. return;
  63823. }
  63824. var types = [];
  63825. var samplingModes = [];
  63826. for (var i = 0; i < count; i++) {
  63827. if (options && options.types && options.types[i] !== undefined) {
  63828. types.push(options.types[i]);
  63829. }
  63830. else {
  63831. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63832. }
  63833. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63834. samplingModes.push(options.samplingModes[i]);
  63835. }
  63836. else {
  63837. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63838. }
  63839. }
  63840. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63841. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63842. _this._size = size;
  63843. _this._multiRenderTargetOptions = {
  63844. samplingModes: samplingModes,
  63845. generateMipMaps: generateMipMaps,
  63846. generateDepthBuffer: generateDepthBuffer,
  63847. generateStencilBuffer: generateStencilBuffer,
  63848. generateDepthTexture: generateDepthTexture,
  63849. types: types,
  63850. textureCount: count
  63851. };
  63852. _this._createInternalTextures();
  63853. _this._createTextures();
  63854. return _this;
  63855. }
  63856. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63857. get: function () {
  63858. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63859. },
  63860. enumerable: true,
  63861. configurable: true
  63862. });
  63863. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63864. get: function () {
  63865. return this._textures;
  63866. },
  63867. enumerable: true,
  63868. configurable: true
  63869. });
  63870. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63871. get: function () {
  63872. return this._textures[this._textures.length - 1];
  63873. },
  63874. enumerable: true,
  63875. configurable: true
  63876. });
  63877. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63878. set: function (wrap) {
  63879. if (this._textures) {
  63880. for (var i = 0; i < this._textures.length; i++) {
  63881. this._textures[i].wrapU = wrap;
  63882. }
  63883. }
  63884. },
  63885. enumerable: true,
  63886. configurable: true
  63887. });
  63888. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63889. set: function (wrap) {
  63890. if (this._textures) {
  63891. for (var i = 0; i < this._textures.length; i++) {
  63892. this._textures[i].wrapV = wrap;
  63893. }
  63894. }
  63895. },
  63896. enumerable: true,
  63897. configurable: true
  63898. });
  63899. MultiRenderTarget.prototype._rebuild = function () {
  63900. this.releaseInternalTextures();
  63901. this._createInternalTextures();
  63902. for (var i = 0; i < this._internalTextures.length; i++) {
  63903. var texture = this._textures[i];
  63904. texture._texture = this._internalTextures[i];
  63905. }
  63906. // Keeps references to frame buffer and stencil/depth buffer
  63907. this._texture = this._internalTextures[0];
  63908. };
  63909. MultiRenderTarget.prototype._createInternalTextures = function () {
  63910. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63911. };
  63912. MultiRenderTarget.prototype._createTextures = function () {
  63913. this._textures = [];
  63914. for (var i = 0; i < this._internalTextures.length; i++) {
  63915. var texture = new BABYLON.Texture(null, this.getScene());
  63916. texture._texture = this._internalTextures[i];
  63917. this._textures.push(texture);
  63918. }
  63919. // Keeps references to frame buffer and stencil/depth buffer
  63920. this._texture = this._internalTextures[0];
  63921. };
  63922. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63923. get: function () {
  63924. return this._samples;
  63925. },
  63926. set: function (value) {
  63927. if (this._samples === value) {
  63928. return;
  63929. }
  63930. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63931. },
  63932. enumerable: true,
  63933. configurable: true
  63934. });
  63935. MultiRenderTarget.prototype.resize = function (size) {
  63936. this.releaseInternalTextures();
  63937. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63938. this._createInternalTextures();
  63939. };
  63940. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63941. var _this = this;
  63942. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  63943. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63944. });
  63945. };
  63946. MultiRenderTarget.prototype.dispose = function () {
  63947. this.releaseInternalTextures();
  63948. _super.prototype.dispose.call(this);
  63949. };
  63950. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  63951. if (!this._internalTextures) {
  63952. return;
  63953. }
  63954. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63955. if (this._internalTextures[i] !== undefined) {
  63956. this._internalTextures[i].dispose();
  63957. this._internalTextures.splice(i, 1);
  63958. }
  63959. }
  63960. };
  63961. return MultiRenderTarget;
  63962. }(BABYLON.RenderTargetTexture));
  63963. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63964. })(BABYLON || (BABYLON = {}));
  63965. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63966. var BABYLON;
  63967. (function (BABYLON) {
  63968. var MirrorTexture = /** @class */ (function (_super) {
  63969. __extends(MirrorTexture, _super);
  63970. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63971. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63972. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63973. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63974. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63975. _this.scene = scene;
  63976. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63977. _this._transformMatrix = BABYLON.Matrix.Zero();
  63978. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  63979. _this._adaptiveBlurKernel = 0;
  63980. _this._blurKernelX = 0;
  63981. _this._blurKernelY = 0;
  63982. _this._blurRatio = 1.0;
  63983. _this.ignoreCameraViewport = true;
  63984. _this._updateGammaSpace();
  63985. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  63986. _this._updateGammaSpace;
  63987. });
  63988. _this.onBeforeRenderObservable.add(function () {
  63989. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  63990. _this._savedViewMatrix = scene.getViewMatrix();
  63991. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  63992. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  63993. scene.clipPlane = _this.mirrorPlane;
  63994. scene.getEngine().cullBackFaces = false;
  63995. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  63996. });
  63997. _this.onAfterRenderObservable.add(function () {
  63998. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  63999. scene.getEngine().cullBackFaces = true;
  64000. scene._mirroredCameraPosition = null;
  64001. delete scene.clipPlane;
  64002. });
  64003. return _this;
  64004. }
  64005. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64006. get: function () {
  64007. return this._blurRatio;
  64008. },
  64009. set: function (value) {
  64010. if (this._blurRatio === value) {
  64011. return;
  64012. }
  64013. this._blurRatio = value;
  64014. this._preparePostProcesses();
  64015. },
  64016. enumerable: true,
  64017. configurable: true
  64018. });
  64019. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64020. set: function (value) {
  64021. this._adaptiveBlurKernel = value;
  64022. this._autoComputeBlurKernel();
  64023. },
  64024. enumerable: true,
  64025. configurable: true
  64026. });
  64027. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64028. set: function (value) {
  64029. this.blurKernelX = value;
  64030. this.blurKernelY = value;
  64031. },
  64032. enumerable: true,
  64033. configurable: true
  64034. });
  64035. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64036. get: function () {
  64037. return this._blurKernelX;
  64038. },
  64039. set: function (value) {
  64040. if (this._blurKernelX === value) {
  64041. return;
  64042. }
  64043. this._blurKernelX = value;
  64044. this._preparePostProcesses();
  64045. },
  64046. enumerable: true,
  64047. configurable: true
  64048. });
  64049. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64050. get: function () {
  64051. return this._blurKernelY;
  64052. },
  64053. set: function (value) {
  64054. if (this._blurKernelY === value) {
  64055. return;
  64056. }
  64057. this._blurKernelY = value;
  64058. this._preparePostProcesses();
  64059. },
  64060. enumerable: true,
  64061. configurable: true
  64062. });
  64063. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64064. var engine = this.getScene().getEngine();
  64065. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64066. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64067. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64068. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64069. };
  64070. MirrorTexture.prototype._onRatioRescale = function () {
  64071. if (this._sizeRatio) {
  64072. this.resize(this._initialSizeParameter);
  64073. if (!this._adaptiveBlurKernel) {
  64074. this._preparePostProcesses();
  64075. }
  64076. }
  64077. if (this._adaptiveBlurKernel) {
  64078. this._autoComputeBlurKernel();
  64079. }
  64080. };
  64081. MirrorTexture.prototype._updateGammaSpace = function () {
  64082. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64083. };
  64084. MirrorTexture.prototype._preparePostProcesses = function () {
  64085. this.clearPostProcesses(true);
  64086. if (this._blurKernelX && this._blurKernelY) {
  64087. var engine = this.getScene().getEngine();
  64088. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64089. 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);
  64090. this._blurX.autoClear = false;
  64091. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64092. this._blurX.inputTexture = this._texture;
  64093. }
  64094. else {
  64095. this._blurX.alwaysForcePOT = true;
  64096. }
  64097. 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);
  64098. this._blurY.autoClear = false;
  64099. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64100. this.addPostProcess(this._blurX);
  64101. this.addPostProcess(this._blurY);
  64102. }
  64103. else {
  64104. if (this._blurY) {
  64105. this.removePostProcess(this._blurY);
  64106. this._blurY.dispose();
  64107. this._blurY = null;
  64108. }
  64109. if (this._blurX) {
  64110. this.removePostProcess(this._blurX);
  64111. this._blurX.dispose();
  64112. this._blurX = null;
  64113. }
  64114. }
  64115. };
  64116. MirrorTexture.prototype.clone = function () {
  64117. var scene = this.getScene();
  64118. if (!scene) {
  64119. return this;
  64120. }
  64121. var textureSize = this.getSize();
  64122. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64123. // Base texture
  64124. newTexture.hasAlpha = this.hasAlpha;
  64125. newTexture.level = this.level;
  64126. // Mirror Texture
  64127. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64128. if (this.renderList) {
  64129. newTexture.renderList = this.renderList.slice(0);
  64130. }
  64131. return newTexture;
  64132. };
  64133. MirrorTexture.prototype.serialize = function () {
  64134. if (!this.name) {
  64135. return null;
  64136. }
  64137. var serializationObject = _super.prototype.serialize.call(this);
  64138. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64139. return serializationObject;
  64140. };
  64141. MirrorTexture.prototype.dispose = function () {
  64142. _super.prototype.dispose.call(this);
  64143. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64144. };
  64145. return MirrorTexture;
  64146. }(BABYLON.RenderTargetTexture));
  64147. BABYLON.MirrorTexture = MirrorTexture;
  64148. })(BABYLON || (BABYLON = {}));
  64149. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64150. var BABYLON;
  64151. (function (BABYLON) {
  64152. /**
  64153. * Creates a refraction texture used by refraction channel of the standard material.
  64154. * @param name the texture name
  64155. * @param size size of the underlying texture
  64156. * @param scene root scene
  64157. */
  64158. var RefractionTexture = /** @class */ (function (_super) {
  64159. __extends(RefractionTexture, _super);
  64160. function RefractionTexture(name, size, scene, generateMipMaps) {
  64161. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64162. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64163. _this.depth = 2.0;
  64164. _this.onBeforeRenderObservable.add(function () {
  64165. scene.clipPlane = _this.refractionPlane;
  64166. });
  64167. _this.onAfterRenderObservable.add(function () {
  64168. delete scene.clipPlane;
  64169. });
  64170. return _this;
  64171. }
  64172. RefractionTexture.prototype.clone = function () {
  64173. var scene = this.getScene();
  64174. if (!scene) {
  64175. return this;
  64176. }
  64177. var textureSize = this.getSize();
  64178. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64179. // Base texture
  64180. newTexture.hasAlpha = this.hasAlpha;
  64181. newTexture.level = this.level;
  64182. // Refraction Texture
  64183. newTexture.refractionPlane = this.refractionPlane.clone();
  64184. if (this.renderList) {
  64185. newTexture.renderList = this.renderList.slice(0);
  64186. }
  64187. newTexture.depth = this.depth;
  64188. return newTexture;
  64189. };
  64190. RefractionTexture.prototype.serialize = function () {
  64191. if (!this.name) {
  64192. return null;
  64193. }
  64194. var serializationObject = _super.prototype.serialize.call(this);
  64195. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64196. serializationObject.depth = this.depth;
  64197. return serializationObject;
  64198. };
  64199. return RefractionTexture;
  64200. }(BABYLON.RenderTargetTexture));
  64201. BABYLON.RefractionTexture = RefractionTexture;
  64202. })(BABYLON || (BABYLON = {}));
  64203. //# sourceMappingURL=babylon.refractionTexture.js.map
  64204. var BABYLON;
  64205. (function (BABYLON) {
  64206. /**
  64207. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64208. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64209. */
  64210. var DynamicTexture = /** @class */ (function (_super) {
  64211. __extends(DynamicTexture, _super);
  64212. /**
  64213. * Creates a {BABYLON.DynamicTexture}
  64214. * @param name defines the name of the texture
  64215. * @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
  64216. * @param scene defines the scene where you want the texture
  64217. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64218. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64219. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64220. */
  64221. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64222. if (scene === void 0) { scene = null; }
  64223. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64224. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64225. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64226. _this.name = name;
  64227. _this._engine = _this.getScene().getEngine();
  64228. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64229. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64230. _this._generateMipMaps = generateMipMaps;
  64231. if (options.getContext) {
  64232. _this._canvas = options;
  64233. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64234. }
  64235. else {
  64236. _this._canvas = document.createElement("canvas");
  64237. if (options.width || options.width === 0) {
  64238. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64239. }
  64240. else {
  64241. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64242. }
  64243. }
  64244. var textureSize = _this.getSize();
  64245. _this._canvas.width = textureSize.width;
  64246. _this._canvas.height = textureSize.height;
  64247. _this._context = _this._canvas.getContext("2d");
  64248. return _this;
  64249. }
  64250. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64251. /**
  64252. * Gets the current state of canRescale
  64253. */
  64254. get: function () {
  64255. return true;
  64256. },
  64257. enumerable: true,
  64258. configurable: true
  64259. });
  64260. DynamicTexture.prototype._recreate = function (textureSize) {
  64261. this._canvas.width = textureSize.width;
  64262. this._canvas.height = textureSize.height;
  64263. this.releaseInternalTexture();
  64264. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64265. };
  64266. /**
  64267. * Scales the texture
  64268. * @param ratio the scale factor to apply to both width and height
  64269. */
  64270. DynamicTexture.prototype.scale = function (ratio) {
  64271. var textureSize = this.getSize();
  64272. textureSize.width *= ratio;
  64273. textureSize.height *= ratio;
  64274. this._recreate(textureSize);
  64275. };
  64276. /**
  64277. * Resizes the texture
  64278. * @param width the new width
  64279. * @param height the new height
  64280. */
  64281. DynamicTexture.prototype.scaleTo = function (width, height) {
  64282. var textureSize = this.getSize();
  64283. textureSize.width = width;
  64284. textureSize.height = height;
  64285. this._recreate(textureSize);
  64286. };
  64287. /**
  64288. * Gets the context of the canvas used by the texture
  64289. * @returns the canvas context of the dynamic texture
  64290. */
  64291. DynamicTexture.prototype.getContext = function () {
  64292. return this._context;
  64293. };
  64294. /**
  64295. * Clears the texture
  64296. */
  64297. DynamicTexture.prototype.clear = function () {
  64298. var size = this.getSize();
  64299. this._context.fillRect(0, 0, size.width, size.height);
  64300. };
  64301. /**
  64302. * Updates the texture
  64303. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64304. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  64305. */
  64306. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64307. if (premulAlpha === void 0) { premulAlpha = false; }
  64308. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  64309. };
  64310. /**
  64311. * Draws text onto the texture
  64312. * @param text defines the text to be drawn
  64313. * @param x defines the placement of the text from the left
  64314. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64315. * @param font defines the font to be used with font-style, font-size, font-name
  64316. * @param color defines the color used for the text
  64317. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64318. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64319. * @param update defines whether texture is immediately update (default is true)
  64320. */
  64321. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64322. if (update === void 0) { update = true; }
  64323. var size = this.getSize();
  64324. if (clearColor) {
  64325. this._context.fillStyle = clearColor;
  64326. this._context.fillRect(0, 0, size.width, size.height);
  64327. }
  64328. this._context.font = font;
  64329. if (x === null || x === undefined) {
  64330. var textSize = this._context.measureText(text);
  64331. x = (size.width - textSize.width) / 2;
  64332. }
  64333. if (y === null || y === undefined) {
  64334. var fontSize = parseInt((font.replace(/\D/g, '')));
  64335. y = (size.height / 2) + (fontSize / 3.65);
  64336. }
  64337. this._context.fillStyle = color;
  64338. this._context.fillText(text, x, y);
  64339. if (update) {
  64340. this.update(invertY);
  64341. }
  64342. };
  64343. /**
  64344. * Clones the texture
  64345. * @returns the clone of the texture.
  64346. */
  64347. DynamicTexture.prototype.clone = function () {
  64348. var scene = this.getScene();
  64349. if (!scene) {
  64350. return this;
  64351. }
  64352. var textureSize = this.getSize();
  64353. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64354. // Base texture
  64355. newTexture.hasAlpha = this.hasAlpha;
  64356. newTexture.level = this.level;
  64357. // Dynamic Texture
  64358. newTexture.wrapU = this.wrapU;
  64359. newTexture.wrapV = this.wrapV;
  64360. return newTexture;
  64361. };
  64362. /** @hidden */
  64363. DynamicTexture.prototype._rebuild = function () {
  64364. this.update();
  64365. };
  64366. return DynamicTexture;
  64367. }(BABYLON.Texture));
  64368. BABYLON.DynamicTexture = DynamicTexture;
  64369. })(BABYLON || (BABYLON = {}));
  64370. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64371. var BABYLON;
  64372. (function (BABYLON) {
  64373. var VideoTexture = /** @class */ (function (_super) {
  64374. __extends(VideoTexture, _super);
  64375. /**
  64376. * Creates a video texture.
  64377. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64378. * @param {string | null} name optional name, will detect from video source, if not defined
  64379. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64380. * @param {BABYLON.Scene} scene is obviously the current scene.
  64381. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64382. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64383. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64384. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64385. */
  64386. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64387. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64388. if (invertY === void 0) { invertY = false; }
  64389. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64390. if (settings === void 0) { settings = {
  64391. autoPlay: true,
  64392. loop: true,
  64393. autoUpdateTexture: true,
  64394. }; }
  64395. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64396. _this._onUserActionRequestedObservable = null;
  64397. _this._stillImageCaptured = false;
  64398. _this._createInternalTexture = function () {
  64399. if (_this._texture != null) {
  64400. return;
  64401. }
  64402. if (!_this._engine.needPOTTextures ||
  64403. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64404. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64405. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64406. }
  64407. else {
  64408. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64409. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64410. _this._generateMipMaps = false;
  64411. }
  64412. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64413. if (!_this.video.autoplay) {
  64414. var oldHandler_1 = _this.video.onplaying;
  64415. var error_1 = false;
  64416. _this.video.onplaying = function () {
  64417. _this.video.onplaying = oldHandler_1;
  64418. _this._texture.isReady = true;
  64419. _this._updateInternalTexture();
  64420. if (!error_1) {
  64421. _this.video.pause();
  64422. }
  64423. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64424. _this.onLoadObservable.notifyObservers(_this);
  64425. }
  64426. };
  64427. var playing = _this.video.play();
  64428. if (playing) {
  64429. playing.then(function () {
  64430. // Everything is good.
  64431. })
  64432. .catch(function () {
  64433. error_1 = true;
  64434. // On Chrome for instance, new policies might prevent playing without user interaction.
  64435. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  64436. _this._onUserActionRequestedObservable.notifyObservers(_this);
  64437. }
  64438. });
  64439. }
  64440. else {
  64441. _this.video.onplaying = oldHandler_1;
  64442. _this._texture.isReady = true;
  64443. _this._updateInternalTexture();
  64444. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64445. _this.onLoadObservable.notifyObservers(_this);
  64446. }
  64447. }
  64448. }
  64449. else {
  64450. _this._texture.isReady = true;
  64451. _this._updateInternalTexture();
  64452. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64453. _this.onLoadObservable.notifyObservers(_this);
  64454. }
  64455. }
  64456. };
  64457. _this.reset = function () {
  64458. if (_this._texture == null) {
  64459. return;
  64460. }
  64461. _this._texture.dispose();
  64462. _this._texture = null;
  64463. };
  64464. _this._updateInternalTexture = function (e) {
  64465. if (_this._texture == null || !_this._texture.isReady) {
  64466. return;
  64467. }
  64468. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64469. return;
  64470. }
  64471. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64472. };
  64473. _this._engine = _this.getScene().getEngine();
  64474. _this._generateMipMaps = generateMipMaps;
  64475. _this._samplingMode = samplingMode;
  64476. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64477. _this.name = name || _this._getName(src);
  64478. _this.video = _this._getVideo(src);
  64479. if (settings.poster) {
  64480. _this.video.poster = settings.poster;
  64481. }
  64482. if (settings.autoPlay !== undefined) {
  64483. _this.video.autoplay = settings.autoPlay;
  64484. }
  64485. if (settings.loop !== undefined) {
  64486. _this.video.loop = settings.loop;
  64487. }
  64488. _this.video.setAttribute("playsinline", "");
  64489. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64490. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64491. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64492. _this.video.addEventListener("emptied", _this.reset);
  64493. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64494. _this._createInternalTexture();
  64495. }
  64496. return _this;
  64497. }
  64498. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  64499. get: function () {
  64500. if (!this._onUserActionRequestedObservable) {
  64501. this._onUserActionRequestedObservable = new BABYLON.Observable();
  64502. }
  64503. return this._onUserActionRequestedObservable;
  64504. },
  64505. enumerable: true,
  64506. configurable: true
  64507. });
  64508. VideoTexture.prototype._getName = function (src) {
  64509. if (src instanceof HTMLVideoElement) {
  64510. return src.currentSrc;
  64511. }
  64512. if (typeof src === "object") {
  64513. return src.toString();
  64514. }
  64515. return src;
  64516. };
  64517. ;
  64518. VideoTexture.prototype._getVideo = function (src) {
  64519. if (src instanceof HTMLVideoElement) {
  64520. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64521. return src;
  64522. }
  64523. var video = document.createElement("video");
  64524. if (typeof src === "string") {
  64525. BABYLON.Tools.SetCorsBehavior(src, video);
  64526. video.src = src;
  64527. }
  64528. else {
  64529. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64530. src.forEach(function (url) {
  64531. var source = document.createElement("source");
  64532. source.src = url;
  64533. video.appendChild(source);
  64534. });
  64535. }
  64536. return video;
  64537. };
  64538. ;
  64539. /**
  64540. * Internal method to initiate `update`.
  64541. */
  64542. VideoTexture.prototype._rebuild = function () {
  64543. this.update();
  64544. };
  64545. /**
  64546. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64547. */
  64548. VideoTexture.prototype.update = function () {
  64549. if (!this.autoUpdateTexture) {
  64550. // Expecting user to call `updateTexture` manually
  64551. return;
  64552. }
  64553. this.updateTexture(true);
  64554. };
  64555. /**
  64556. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64557. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64558. */
  64559. VideoTexture.prototype.updateTexture = function (isVisible) {
  64560. if (!isVisible) {
  64561. return;
  64562. }
  64563. if (this.video.paused && this._stillImageCaptured) {
  64564. return;
  64565. }
  64566. this._stillImageCaptured = true;
  64567. this._updateInternalTexture();
  64568. };
  64569. /**
  64570. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64571. * @param url New url.
  64572. */
  64573. VideoTexture.prototype.updateURL = function (url) {
  64574. this.video.src = url;
  64575. };
  64576. VideoTexture.prototype.dispose = function () {
  64577. _super.prototype.dispose.call(this);
  64578. if (this._onUserActionRequestedObservable) {
  64579. this._onUserActionRequestedObservable.clear();
  64580. this._onUserActionRequestedObservable = null;
  64581. }
  64582. this.video.removeEventListener("canplay", this._createInternalTexture);
  64583. this.video.removeEventListener("paused", this._updateInternalTexture);
  64584. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64585. this.video.removeEventListener("emptied", this.reset);
  64586. this.video.pause();
  64587. };
  64588. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64589. var video = document.createElement("video");
  64590. var constraintsDeviceId;
  64591. if (constraints && constraints.deviceId) {
  64592. constraintsDeviceId = {
  64593. exact: constraints.deviceId,
  64594. };
  64595. }
  64596. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64597. if (navigator.mediaDevices) {
  64598. navigator.mediaDevices.getUserMedia({ video: constraints })
  64599. .then(function (stream) {
  64600. if (video.mozSrcObject !== undefined) {
  64601. // hack for Firefox < 19
  64602. video.mozSrcObject = stream;
  64603. }
  64604. else {
  64605. video.srcObject = stream;
  64606. }
  64607. var onPlaying = function () {
  64608. if (onReady) {
  64609. onReady(new VideoTexture("video", video, scene, true, true));
  64610. }
  64611. video.removeEventListener("playing", onPlaying);
  64612. };
  64613. video.addEventListener("playing", onPlaying);
  64614. video.play();
  64615. })
  64616. .catch(function (err) {
  64617. BABYLON.Tools.Error(err.name);
  64618. });
  64619. }
  64620. else {
  64621. navigator.getUserMedia =
  64622. navigator.getUserMedia ||
  64623. navigator.webkitGetUserMedia ||
  64624. navigator.mozGetUserMedia ||
  64625. navigator.msGetUserMedia;
  64626. if (navigator.getUserMedia) {
  64627. navigator.getUserMedia({
  64628. video: {
  64629. deviceId: constraintsDeviceId,
  64630. width: {
  64631. min: (constraints && constraints.minWidth) || 256,
  64632. max: (constraints && constraints.maxWidth) || 640,
  64633. },
  64634. height: {
  64635. min: (constraints && constraints.minHeight) || 256,
  64636. max: (constraints && constraints.maxHeight) || 480,
  64637. },
  64638. },
  64639. }, function (stream) {
  64640. if (video.mozSrcObject !== undefined) {
  64641. // hack for Firefox < 19
  64642. video.mozSrcObject = stream;
  64643. }
  64644. else {
  64645. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64646. }
  64647. video.play();
  64648. if (onReady) {
  64649. onReady(new VideoTexture("video", video, scene, true, true));
  64650. }
  64651. }, function (e) {
  64652. BABYLON.Tools.Error(e.name);
  64653. });
  64654. }
  64655. }
  64656. };
  64657. return VideoTexture;
  64658. }(BABYLON.Texture));
  64659. BABYLON.VideoTexture = VideoTexture;
  64660. })(BABYLON || (BABYLON = {}));
  64661. //# sourceMappingURL=babylon.videoTexture.js.map
  64662. var BABYLON;
  64663. (function (BABYLON) {
  64664. var RawTexture = /** @class */ (function (_super) {
  64665. __extends(RawTexture, _super);
  64666. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64667. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64668. if (invertY === void 0) { invertY = false; }
  64669. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64670. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64671. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64672. _this.format = format;
  64673. _this._engine = scene.getEngine();
  64674. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64675. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64676. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64677. return _this;
  64678. }
  64679. RawTexture.prototype.update = function (data) {
  64680. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64681. };
  64682. // Statics
  64683. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64684. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64685. if (invertY === void 0) { invertY = false; }
  64686. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64687. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64688. };
  64689. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64690. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64691. if (invertY === void 0) { invertY = false; }
  64692. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64693. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64694. };
  64695. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64696. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64697. if (invertY === void 0) { invertY = false; }
  64698. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64699. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64700. };
  64701. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64702. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64703. if (invertY === void 0) { invertY = false; }
  64704. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64705. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64706. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64707. };
  64708. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64709. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64710. if (invertY === void 0) { invertY = false; }
  64711. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64712. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64713. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64714. };
  64715. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64716. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64717. if (invertY === void 0) { invertY = false; }
  64718. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64719. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  64720. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  64721. };
  64722. return RawTexture;
  64723. }(BABYLON.Texture));
  64724. BABYLON.RawTexture = RawTexture;
  64725. })(BABYLON || (BABYLON = {}));
  64726. //# sourceMappingURL=babylon.rawTexture.js.map
  64727. var BABYLON;
  64728. (function (BABYLON) {
  64729. /**
  64730. * Class used to store 3D textures containing user data
  64731. */
  64732. var RawTexture3D = /** @class */ (function (_super) {
  64733. __extends(RawTexture3D, _super);
  64734. /**
  64735. * Create a new RawTexture3D
  64736. * @param data defines the data of the texture
  64737. * @param width defines the width of the texture
  64738. * @param height defines the height of the texture
  64739. * @param depth defines the depth of the texture
  64740. * @param format defines the texture format to use
  64741. * @param scene defines the hosting scene
  64742. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64743. * @param invertY defines if texture must be stored with Y axis inverted
  64744. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64745. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  64746. */
  64747. function RawTexture3D(data, width, height, depth,
  64748. /** Gets or sets the texture format to use */
  64749. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  64750. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64751. if (invertY === void 0) { invertY = false; }
  64752. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64753. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64754. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64755. _this.format = format;
  64756. _this._engine = scene.getEngine();
  64757. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  64758. _this.is3D = true;
  64759. return _this;
  64760. }
  64761. /**
  64762. * Update the texture with new data
  64763. * @param data defines the data to store in the texture
  64764. */
  64765. RawTexture3D.prototype.update = function (data) {
  64766. if (!this._texture) {
  64767. return;
  64768. }
  64769. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64770. };
  64771. return RawTexture3D;
  64772. }(BABYLON.Texture));
  64773. BABYLON.RawTexture3D = RawTexture3D;
  64774. })(BABYLON || (BABYLON = {}));
  64775. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64776. var BABYLON;
  64777. (function (BABYLON) {
  64778. /**
  64779. * PostProcessManager is used to manage one or more post processes or post process pipelines
  64780. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64781. */
  64782. var PostProcessManager = /** @class */ (function () {
  64783. /**
  64784. * Creates a new instance PostProcess
  64785. * @param scene The scene that the post process is associated with.
  64786. */
  64787. function PostProcessManager(scene) {
  64788. this._vertexBuffers = {};
  64789. this._scene = scene;
  64790. }
  64791. PostProcessManager.prototype._prepareBuffers = function () {
  64792. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  64793. return;
  64794. }
  64795. // VBO
  64796. var vertices = [];
  64797. vertices.push(1, 1);
  64798. vertices.push(-1, 1);
  64799. vertices.push(-1, -1);
  64800. vertices.push(1, -1);
  64801. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64802. this._buildIndexBuffer();
  64803. };
  64804. PostProcessManager.prototype._buildIndexBuffer = function () {
  64805. // Indices
  64806. var indices = [];
  64807. indices.push(0);
  64808. indices.push(1);
  64809. indices.push(2);
  64810. indices.push(0);
  64811. indices.push(2);
  64812. indices.push(3);
  64813. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  64814. };
  64815. /**
  64816. * Rebuilds the vertex buffers of the manager.
  64817. */
  64818. PostProcessManager.prototype._rebuild = function () {
  64819. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64820. if (!vb) {
  64821. return;
  64822. }
  64823. vb._rebuild();
  64824. this._buildIndexBuffer();
  64825. };
  64826. // Methods
  64827. /**
  64828. * Prepares a frame to be run through a post process.
  64829. * @param sourceTexture The input texture to the post procesess. (default: null)
  64830. * @param postProcesses An array of post processes to be run. (default: null)
  64831. * @returns True if the post processes were able to be run.
  64832. */
  64833. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  64834. if (sourceTexture === void 0) { sourceTexture = null; }
  64835. if (postProcesses === void 0) { postProcesses = null; }
  64836. var camera = this._scene.activeCamera;
  64837. if (!camera) {
  64838. return false;
  64839. }
  64840. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  64841. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  64842. return false;
  64843. }
  64844. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  64845. return true;
  64846. };
  64847. /**
  64848. * Manually render a set of post processes to a texture.
  64849. * @param postProcesses An array of post processes to be run.
  64850. * @param targetTexture The target texture to render to.
  64851. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  64852. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  64853. * @param lodLevel defines which lod of the texture to render to
  64854. */
  64855. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  64856. if (targetTexture === void 0) { targetTexture = null; }
  64857. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  64858. if (faceIndex === void 0) { faceIndex = 0; }
  64859. if (lodLevel === void 0) { lodLevel = 0; }
  64860. var engine = this._scene.getEngine();
  64861. for (var index = 0; index < postProcesses.length; index++) {
  64862. if (index < postProcesses.length - 1) {
  64863. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  64864. }
  64865. else {
  64866. if (targetTexture) {
  64867. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  64868. }
  64869. else {
  64870. engine.restoreDefaultFramebuffer();
  64871. }
  64872. }
  64873. var pp = postProcesses[index];
  64874. var effect = pp.apply();
  64875. if (effect) {
  64876. pp.onBeforeRenderObservable.notifyObservers(effect);
  64877. // VBOs
  64878. this._prepareBuffers();
  64879. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  64880. // Draw order
  64881. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64882. pp.onAfterRenderObservable.notifyObservers(effect);
  64883. }
  64884. }
  64885. // Restore depth buffer
  64886. engine.setDepthBuffer(true);
  64887. engine.setDepthWrite(true);
  64888. };
  64889. /**
  64890. * Finalize the result of the output of the postprocesses.
  64891. * @param doNotPresent If true the result will not be displayed to the screen.
  64892. * @param targetTexture The target texture to render to.
  64893. * @param faceIndex The index of the face to bind the target texture to.
  64894. * @param postProcesses The array of post processes to render.
  64895. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  64896. */
  64897. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  64898. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  64899. var camera = this._scene.activeCamera;
  64900. if (!camera) {
  64901. return;
  64902. }
  64903. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  64904. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  64905. return;
  64906. }
  64907. var engine = this._scene.getEngine();
  64908. for (var index = 0, len = postProcesses.length; index < len; index++) {
  64909. var pp = postProcesses[index];
  64910. if (index < len - 1) {
  64911. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  64912. }
  64913. else {
  64914. if (targetTexture) {
  64915. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  64916. pp._outputTexture = targetTexture;
  64917. }
  64918. else {
  64919. engine.restoreDefaultFramebuffer();
  64920. pp._outputTexture = null;
  64921. }
  64922. }
  64923. if (doNotPresent) {
  64924. break;
  64925. }
  64926. var effect = pp.apply();
  64927. if (effect) {
  64928. pp.onBeforeRenderObservable.notifyObservers(effect);
  64929. // VBOs
  64930. this._prepareBuffers();
  64931. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  64932. // Draw order
  64933. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64934. pp.onAfterRenderObservable.notifyObservers(effect);
  64935. }
  64936. }
  64937. // Restore states
  64938. engine.setDepthBuffer(true);
  64939. engine.setDepthWrite(true);
  64940. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64941. };
  64942. /**
  64943. * Disposes of the post process manager.
  64944. */
  64945. PostProcessManager.prototype.dispose = function () {
  64946. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64947. if (buffer) {
  64948. buffer.dispose();
  64949. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64950. }
  64951. if (this._indexBuffer) {
  64952. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64953. this._indexBuffer = null;
  64954. }
  64955. };
  64956. return PostProcessManager;
  64957. }());
  64958. BABYLON.PostProcessManager = PostProcessManager;
  64959. })(BABYLON || (BABYLON = {}));
  64960. //# sourceMappingURL=babylon.postProcessManager.js.map
  64961. var BABYLON;
  64962. (function (BABYLON) {
  64963. /**
  64964. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64965. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64966. */
  64967. var PostProcess = /** @class */ (function () {
  64968. /**
  64969. * Creates a new instance PostProcess
  64970. * @param name The name of the PostProcess.
  64971. * @param fragmentUrl The url of the fragment shader to be used.
  64972. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64973. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64974. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64975. * @param camera The camera to apply the render pass to.
  64976. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64977. * @param engine The engine which the post process will be applied. (default: current engine)
  64978. * @param reusable If the post process can be reused on the same frame. (default: false)
  64979. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64980. * @param textureType Type of textures used when performing the post process. (default: 0)
  64981. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64982. * @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
  64983. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64984. */
  64985. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64986. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64987. if (defines === void 0) { defines = null; }
  64988. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64989. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64990. if (blockCompilation === void 0) { blockCompilation = false; }
  64991. this.name = name;
  64992. /**
  64993. * Width of the texture to apply the post process on
  64994. */
  64995. this.width = -1;
  64996. /**
  64997. * Height of the texture to apply the post process on
  64998. */
  64999. this.height = -1;
  65000. /**
  65001. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65002. */
  65003. this._outputTexture = null;
  65004. /**
  65005. * If the buffer needs to be cleared before applying the post process. (default: true)
  65006. * Should be set to false if shader will overwrite all previous pixels.
  65007. */
  65008. this.autoClear = true;
  65009. /**
  65010. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65011. */
  65012. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65013. /**
  65014. * Animations to be used for the post processing
  65015. */
  65016. this.animations = new Array();
  65017. /**
  65018. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65019. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65020. */
  65021. this.enablePixelPerfectMode = false;
  65022. /**
  65023. * Force the postprocess to be applied without taking in account viewport
  65024. */
  65025. this.forceFullscreenViewport = true;
  65026. /**
  65027. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65028. *
  65029. * | Value | Type | Description |
  65030. * | ----- | ----------------------------------- | ----------- |
  65031. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65032. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65033. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65034. *
  65035. */
  65036. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65037. /**
  65038. * Force textures to be a power of two (default: false)
  65039. */
  65040. this.alwaysForcePOT = false;
  65041. /**
  65042. * Number of sample textures (default: 1)
  65043. */
  65044. this.samples = 1;
  65045. /**
  65046. * Modify the scale of the post process to be the same as the viewport (default: false)
  65047. */
  65048. this.adaptScaleToCurrentViewport = false;
  65049. this._reusable = false;
  65050. /**
  65051. * Smart array of input and output textures for the post process.
  65052. */
  65053. this._textures = new BABYLON.SmartArray(2);
  65054. /**
  65055. * The index in _textures that corresponds to the output texture.
  65056. */
  65057. this._currentRenderTextureInd = 0;
  65058. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65059. this._texelSize = BABYLON.Vector2.Zero();
  65060. // Events
  65061. /**
  65062. * An event triggered when the postprocess is activated.
  65063. */
  65064. this.onActivateObservable = new BABYLON.Observable();
  65065. /**
  65066. * An event triggered when the postprocess changes its size.
  65067. */
  65068. this.onSizeChangedObservable = new BABYLON.Observable();
  65069. /**
  65070. * An event triggered when the postprocess applies its effect.
  65071. */
  65072. this.onApplyObservable = new BABYLON.Observable();
  65073. /**
  65074. * An event triggered before rendering the postprocess
  65075. */
  65076. this.onBeforeRenderObservable = new BABYLON.Observable();
  65077. /**
  65078. * An event triggered after rendering the postprocess
  65079. */
  65080. this.onAfterRenderObservable = new BABYLON.Observable();
  65081. if (camera != null) {
  65082. this._camera = camera;
  65083. this._scene = camera.getScene();
  65084. camera.attachPostProcess(this);
  65085. this._engine = this._scene.getEngine();
  65086. this._scene.postProcesses.push(this);
  65087. }
  65088. else if (engine) {
  65089. this._engine = engine;
  65090. this._engine.postProcesses.push(this);
  65091. }
  65092. this._options = options;
  65093. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65094. this._reusable = reusable || false;
  65095. this._textureType = textureType;
  65096. this._samplers = samplers || [];
  65097. this._samplers.push("textureSampler");
  65098. this._fragmentUrl = fragmentUrl;
  65099. this._vertexUrl = vertexUrl;
  65100. this._parameters = parameters || [];
  65101. this._parameters.push("scale");
  65102. this._indexParameters = indexParameters;
  65103. if (!blockCompilation) {
  65104. this.updateEffect(defines);
  65105. }
  65106. }
  65107. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65108. /**
  65109. * A function that is added to the onActivateObservable
  65110. */
  65111. set: function (callback) {
  65112. if (this._onActivateObserver) {
  65113. this.onActivateObservable.remove(this._onActivateObserver);
  65114. }
  65115. if (callback) {
  65116. this._onActivateObserver = this.onActivateObservable.add(callback);
  65117. }
  65118. },
  65119. enumerable: true,
  65120. configurable: true
  65121. });
  65122. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65123. /**
  65124. * A function that is added to the onSizeChangedObservable
  65125. */
  65126. set: function (callback) {
  65127. if (this._onSizeChangedObserver) {
  65128. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65129. }
  65130. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65131. },
  65132. enumerable: true,
  65133. configurable: true
  65134. });
  65135. Object.defineProperty(PostProcess.prototype, "onApply", {
  65136. /**
  65137. * A function that is added to the onApplyObservable
  65138. */
  65139. set: function (callback) {
  65140. if (this._onApplyObserver) {
  65141. this.onApplyObservable.remove(this._onApplyObserver);
  65142. }
  65143. this._onApplyObserver = this.onApplyObservable.add(callback);
  65144. },
  65145. enumerable: true,
  65146. configurable: true
  65147. });
  65148. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65149. /**
  65150. * A function that is added to the onBeforeRenderObservable
  65151. */
  65152. set: function (callback) {
  65153. if (this._onBeforeRenderObserver) {
  65154. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65155. }
  65156. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65157. },
  65158. enumerable: true,
  65159. configurable: true
  65160. });
  65161. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65162. /**
  65163. * A function that is added to the onAfterRenderObservable
  65164. */
  65165. set: function (callback) {
  65166. if (this._onAfterRenderObserver) {
  65167. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65168. }
  65169. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65170. },
  65171. enumerable: true,
  65172. configurable: true
  65173. });
  65174. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65175. /**
  65176. * 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
  65177. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65178. */
  65179. get: function () {
  65180. return this._textures.data[this._currentRenderTextureInd];
  65181. },
  65182. set: function (value) {
  65183. this._forcedOutputTexture = value;
  65184. },
  65185. enumerable: true,
  65186. configurable: true
  65187. });
  65188. /**
  65189. * Gets the camera which post process is applied to.
  65190. * @returns The camera the post process is applied to.
  65191. */
  65192. PostProcess.prototype.getCamera = function () {
  65193. return this._camera;
  65194. };
  65195. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65196. /**
  65197. * Gets the texel size of the postprocess.
  65198. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65199. */
  65200. get: function () {
  65201. if (this._shareOutputWithPostProcess) {
  65202. return this._shareOutputWithPostProcess.texelSize;
  65203. }
  65204. if (this._forcedOutputTexture) {
  65205. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65206. }
  65207. return this._texelSize;
  65208. },
  65209. enumerable: true,
  65210. configurable: true
  65211. });
  65212. /**
  65213. * Gets the engine which this post process belongs to.
  65214. * @returns The engine the post process was enabled with.
  65215. */
  65216. PostProcess.prototype.getEngine = function () {
  65217. return this._engine;
  65218. };
  65219. /**
  65220. * The effect that is created when initializing the post process.
  65221. * @returns The created effect corrisponding the the postprocess.
  65222. */
  65223. PostProcess.prototype.getEffect = function () {
  65224. return this._effect;
  65225. };
  65226. /**
  65227. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65228. * @param postProcess The post process to share the output with.
  65229. * @returns This post process.
  65230. */
  65231. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65232. this._disposeTextures();
  65233. this._shareOutputWithPostProcess = postProcess;
  65234. return this;
  65235. };
  65236. /**
  65237. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65238. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65239. */
  65240. PostProcess.prototype.useOwnOutput = function () {
  65241. if (this._textures.length == 0) {
  65242. this._textures = new BABYLON.SmartArray(2);
  65243. }
  65244. this._shareOutputWithPostProcess = null;
  65245. };
  65246. /**
  65247. * Updates the effect with the current post process compile time values and recompiles the shader.
  65248. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65249. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65250. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65251. * @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
  65252. * @param onCompiled Called when the shader has been compiled.
  65253. * @param onError Called if there is an error when compiling a shader.
  65254. */
  65255. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65256. if (defines === void 0) { defines = null; }
  65257. if (uniforms === void 0) { uniforms = null; }
  65258. if (samplers === void 0) { samplers = null; }
  65259. 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);
  65260. };
  65261. /**
  65262. * The post process is reusable if it can be used multiple times within one frame.
  65263. * @returns If the post process is reusable
  65264. */
  65265. PostProcess.prototype.isReusable = function () {
  65266. return this._reusable;
  65267. };
  65268. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65269. PostProcess.prototype.markTextureDirty = function () {
  65270. this.width = -1;
  65271. };
  65272. /**
  65273. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65274. * 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.
  65275. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65276. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65277. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65278. * @returns The target texture that was bound to be written to.
  65279. */
  65280. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65281. var _this = this;
  65282. if (sourceTexture === void 0) { sourceTexture = null; }
  65283. camera = camera || this._camera;
  65284. var scene = camera.getScene();
  65285. var engine = scene.getEngine();
  65286. var maxSize = engine.getCaps().maxTextureSize;
  65287. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65288. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65289. // 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
  65290. var webVRCamera = camera.parent;
  65291. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65292. requiredWidth /= 2;
  65293. }
  65294. var desiredWidth = (this._options.width || requiredWidth);
  65295. var desiredHeight = this._options.height || requiredHeight;
  65296. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65297. if (this.adaptScaleToCurrentViewport) {
  65298. var currentViewport = engine.currentViewport;
  65299. if (currentViewport) {
  65300. desiredWidth *= currentViewport.width;
  65301. desiredHeight *= currentViewport.height;
  65302. }
  65303. }
  65304. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65305. if (!this._options.width) {
  65306. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65307. }
  65308. if (!this._options.height) {
  65309. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65310. }
  65311. }
  65312. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65313. if (this._textures.length > 0) {
  65314. for (var i = 0; i < this._textures.length; i++) {
  65315. this._engine._releaseTexture(this._textures.data[i]);
  65316. }
  65317. this._textures.reset();
  65318. }
  65319. this.width = desiredWidth;
  65320. this.height = desiredHeight;
  65321. var textureSize = { width: this.width, height: this.height };
  65322. var textureOptions = {
  65323. generateMipMaps: false,
  65324. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65325. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65326. samplingMode: this.renderTargetSamplingMode,
  65327. type: this._textureType
  65328. };
  65329. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65330. if (this._reusable) {
  65331. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65332. }
  65333. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65334. this.onSizeChangedObservable.notifyObservers(this);
  65335. }
  65336. this._textures.forEach(function (texture) {
  65337. if (texture.samples !== _this.samples) {
  65338. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65339. }
  65340. });
  65341. }
  65342. var target;
  65343. if (this._shareOutputWithPostProcess) {
  65344. target = this._shareOutputWithPostProcess.inputTexture;
  65345. }
  65346. else if (this._forcedOutputTexture) {
  65347. target = this._forcedOutputTexture;
  65348. this.width = this._forcedOutputTexture.width;
  65349. this.height = this._forcedOutputTexture.height;
  65350. }
  65351. else {
  65352. target = this.inputTexture;
  65353. }
  65354. // Bind the input of this post process to be used as the output of the previous post process.
  65355. if (this.enablePixelPerfectMode) {
  65356. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65357. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65358. }
  65359. else {
  65360. this._scaleRatio.copyFromFloats(1, 1);
  65361. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65362. }
  65363. this.onActivateObservable.notifyObservers(camera);
  65364. // Clear
  65365. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65366. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65367. }
  65368. if (this._reusable) {
  65369. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65370. }
  65371. return target;
  65372. };
  65373. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65374. /**
  65375. * If the post process is supported.
  65376. */
  65377. get: function () {
  65378. return this._effect.isSupported;
  65379. },
  65380. enumerable: true,
  65381. configurable: true
  65382. });
  65383. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65384. /**
  65385. * The aspect ratio of the output texture.
  65386. */
  65387. get: function () {
  65388. if (this._shareOutputWithPostProcess) {
  65389. return this._shareOutputWithPostProcess.aspectRatio;
  65390. }
  65391. if (this._forcedOutputTexture) {
  65392. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65393. }
  65394. return this.width / this.height;
  65395. },
  65396. enumerable: true,
  65397. configurable: true
  65398. });
  65399. /**
  65400. * Get a value indicating if the post-process is ready to be used
  65401. * @returns true if the post-process is ready (shader is compiled)
  65402. */
  65403. PostProcess.prototype.isReady = function () {
  65404. return this._effect && this._effect.isReady();
  65405. };
  65406. /**
  65407. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65408. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65409. */
  65410. PostProcess.prototype.apply = function () {
  65411. // Check
  65412. if (!this._effect || !this._effect.isReady())
  65413. return null;
  65414. // States
  65415. this._engine.enableEffect(this._effect);
  65416. this._engine.setState(false);
  65417. this._engine.setDepthBuffer(false);
  65418. this._engine.setDepthWrite(false);
  65419. // Alpha
  65420. this._engine.setAlphaMode(this.alphaMode);
  65421. if (this.alphaConstants) {
  65422. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65423. }
  65424. // Bind the output texture of the preivous post process as the input to this post process.
  65425. var source;
  65426. if (this._shareOutputWithPostProcess) {
  65427. source = this._shareOutputWithPostProcess.inputTexture;
  65428. }
  65429. else if (this._forcedOutputTexture) {
  65430. source = this._forcedOutputTexture;
  65431. }
  65432. else {
  65433. source = this.inputTexture;
  65434. }
  65435. this._effect._bindTexture("textureSampler", source);
  65436. // Parameters
  65437. this._effect.setVector2("scale", this._scaleRatio);
  65438. this.onApplyObservable.notifyObservers(this._effect);
  65439. return this._effect;
  65440. };
  65441. PostProcess.prototype._disposeTextures = function () {
  65442. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65443. return;
  65444. }
  65445. if (this._textures.length > 0) {
  65446. for (var i = 0; i < this._textures.length; i++) {
  65447. this._engine._releaseTexture(this._textures.data[i]);
  65448. }
  65449. }
  65450. this._textures.dispose();
  65451. };
  65452. /**
  65453. * Disposes the post process.
  65454. * @param camera The camera to dispose the post process on.
  65455. */
  65456. PostProcess.prototype.dispose = function (camera) {
  65457. camera = camera || this._camera;
  65458. this._disposeTextures();
  65459. if (this._scene) {
  65460. var index_1 = this._scene.postProcesses.indexOf(this);
  65461. if (index_1 !== -1) {
  65462. this._scene.postProcesses.splice(index_1, 1);
  65463. }
  65464. }
  65465. else {
  65466. var index_2 = this._engine.postProcesses.indexOf(this);
  65467. if (index_2 !== -1) {
  65468. this._engine.postProcesses.splice(index_2, 1);
  65469. }
  65470. }
  65471. if (!camera) {
  65472. return;
  65473. }
  65474. camera.detachPostProcess(this);
  65475. var index = camera._postProcesses.indexOf(this);
  65476. if (index === 0 && camera._postProcesses.length > 0) {
  65477. var firstPostProcess = this._camera._getFirstPostProcess();
  65478. if (firstPostProcess) {
  65479. firstPostProcess.markTextureDirty();
  65480. }
  65481. }
  65482. this.onActivateObservable.clear();
  65483. this.onAfterRenderObservable.clear();
  65484. this.onApplyObservable.clear();
  65485. this.onBeforeRenderObservable.clear();
  65486. this.onSizeChangedObservable.clear();
  65487. };
  65488. return PostProcess;
  65489. }());
  65490. BABYLON.PostProcess = PostProcess;
  65491. })(BABYLON || (BABYLON = {}));
  65492. //# sourceMappingURL=babylon.postProcess.js.map
  65493. var BABYLON;
  65494. (function (BABYLON) {
  65495. var PassPostProcess = /** @class */ (function (_super) {
  65496. __extends(PassPostProcess, _super);
  65497. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65498. if (camera === void 0) { camera = null; }
  65499. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65500. if (blockCompilation === void 0) { blockCompilation = false; }
  65501. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65502. }
  65503. return PassPostProcess;
  65504. }(BABYLON.PostProcess));
  65505. BABYLON.PassPostProcess = PassPostProcess;
  65506. })(BABYLON || (BABYLON = {}));
  65507. //# sourceMappingURL=babylon.passPostProcess.js.map
  65508. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65509. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65510. s = arguments[i];
  65511. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65512. t[p] = s[p];
  65513. }
  65514. return t;
  65515. };
  65516. var BABYLON;
  65517. (function (BABYLON) {
  65518. /**
  65519. * Default implementation IShadowGenerator.
  65520. * This is the main object responsible of generating shadows in the framework.
  65521. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65522. */
  65523. var ShadowGenerator = /** @class */ (function () {
  65524. /**
  65525. * Creates a ShadowGenerator object.
  65526. * A ShadowGenerator is the required tool to use the shadows.
  65527. * Each light casting shadows needs to use its own ShadowGenerator.
  65528. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65529. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65530. * @param light The light object generating the shadows.
  65531. * @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.
  65532. */
  65533. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65534. this._bias = 0.00005;
  65535. this._normalBias = 0;
  65536. this._blurBoxOffset = 1;
  65537. this._blurScale = 2;
  65538. this._blurKernel = 1;
  65539. this._useKernelBlur = false;
  65540. this._filter = ShadowGenerator.FILTER_NONE;
  65541. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65542. this._contactHardeningLightSizeUVRatio = 0.1;
  65543. this._darkness = 0;
  65544. this._transparencyShadow = false;
  65545. /**
  65546. * Controls the extent to which the shadows fade out at the edge of the frustum
  65547. * Used only by directionals and spots
  65548. */
  65549. this.frustumEdgeFalloff = 0;
  65550. /**
  65551. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65552. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65553. * It might on the other hand introduce peter panning.
  65554. */
  65555. this.forceBackFacesOnly = false;
  65556. this._lightDirection = BABYLON.Vector3.Zero();
  65557. this._viewMatrix = BABYLON.Matrix.Zero();
  65558. this._projectionMatrix = BABYLON.Matrix.Zero();
  65559. this._transformMatrix = BABYLON.Matrix.Zero();
  65560. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65561. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65562. this._currentFaceIndex = 0;
  65563. this._currentFaceIndexCache = 0;
  65564. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65565. this._mapSize = mapSize;
  65566. this._light = light;
  65567. this._scene = light.getScene();
  65568. light._shadowGenerator = this;
  65569. // Texture type fallback from float to int if not supported.
  65570. var caps = this._scene.getEngine().getCaps();
  65571. if (!useFullFloatFirst) {
  65572. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65573. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65574. }
  65575. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65576. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65577. }
  65578. else {
  65579. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65580. }
  65581. }
  65582. else {
  65583. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65584. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65585. }
  65586. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65587. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65588. }
  65589. else {
  65590. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65591. }
  65592. }
  65593. this._initializeGenerator();
  65594. this._applyFilterValues();
  65595. }
  65596. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65597. /**
  65598. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65599. */
  65600. get: function () {
  65601. return this._bias;
  65602. },
  65603. /**
  65604. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65605. */
  65606. set: function (bias) {
  65607. this._bias = bias;
  65608. },
  65609. enumerable: true,
  65610. configurable: true
  65611. });
  65612. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65613. /**
  65614. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65615. */
  65616. get: function () {
  65617. return this._normalBias;
  65618. },
  65619. /**
  65620. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65621. */
  65622. set: function (normalBias) {
  65623. this._normalBias = normalBias;
  65624. },
  65625. enumerable: true,
  65626. configurable: true
  65627. });
  65628. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65629. /**
  65630. * Gets the blur box offset: offset applied during the blur pass.
  65631. * Only usefull if useKernelBlur = false
  65632. */
  65633. get: function () {
  65634. return this._blurBoxOffset;
  65635. },
  65636. /**
  65637. * Sets the blur box offset: offset applied during the blur pass.
  65638. * Only usefull if useKernelBlur = false
  65639. */
  65640. set: function (value) {
  65641. if (this._blurBoxOffset === value) {
  65642. return;
  65643. }
  65644. this._blurBoxOffset = value;
  65645. this._disposeBlurPostProcesses();
  65646. },
  65647. enumerable: true,
  65648. configurable: true
  65649. });
  65650. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65651. /**
  65652. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65653. * 2 means half of the size.
  65654. */
  65655. get: function () {
  65656. return this._blurScale;
  65657. },
  65658. /**
  65659. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65660. * 2 means half of the size.
  65661. */
  65662. set: function (value) {
  65663. if (this._blurScale === value) {
  65664. return;
  65665. }
  65666. this._blurScale = value;
  65667. this._disposeBlurPostProcesses();
  65668. },
  65669. enumerable: true,
  65670. configurable: true
  65671. });
  65672. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65673. /**
  65674. * Gets the blur kernel: kernel size of the blur pass.
  65675. * Only usefull if useKernelBlur = true
  65676. */
  65677. get: function () {
  65678. return this._blurKernel;
  65679. },
  65680. /**
  65681. * Sets the blur kernel: kernel size of the blur pass.
  65682. * Only usefull if useKernelBlur = true
  65683. */
  65684. set: function (value) {
  65685. if (this._blurKernel === value) {
  65686. return;
  65687. }
  65688. this._blurKernel = value;
  65689. this._disposeBlurPostProcesses();
  65690. },
  65691. enumerable: true,
  65692. configurable: true
  65693. });
  65694. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65695. /**
  65696. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65697. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65698. */
  65699. get: function () {
  65700. return this._useKernelBlur;
  65701. },
  65702. /**
  65703. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65704. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65705. */
  65706. set: function (value) {
  65707. if (this._useKernelBlur === value) {
  65708. return;
  65709. }
  65710. this._useKernelBlur = value;
  65711. this._disposeBlurPostProcesses();
  65712. },
  65713. enumerable: true,
  65714. configurable: true
  65715. });
  65716. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65717. /**
  65718. * Gets the depth scale used in ESM mode.
  65719. */
  65720. get: function () {
  65721. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65722. },
  65723. /**
  65724. * Sets the depth scale used in ESM mode.
  65725. * This can override the scale stored on the light.
  65726. */
  65727. set: function (value) {
  65728. this._depthScale = value;
  65729. },
  65730. enumerable: true,
  65731. configurable: true
  65732. });
  65733. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65734. /**
  65735. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65736. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65737. */
  65738. get: function () {
  65739. return this._filter;
  65740. },
  65741. /**
  65742. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65743. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65744. */
  65745. set: function (value) {
  65746. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65747. if (this._light.needCube()) {
  65748. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65749. this.useExponentialShadowMap = true;
  65750. return;
  65751. }
  65752. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65753. this.useCloseExponentialShadowMap = true;
  65754. return;
  65755. }
  65756. // PCF on cubemap would also be expensive
  65757. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65758. this.usePoissonSampling = true;
  65759. return;
  65760. }
  65761. }
  65762. // Weblg1 fallback for PCF.
  65763. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65764. if (this._scene.getEngine().webGLVersion === 1) {
  65765. this.usePoissonSampling = true;
  65766. return;
  65767. }
  65768. }
  65769. if (this._filter === value) {
  65770. return;
  65771. }
  65772. this._filter = value;
  65773. this._disposeBlurPostProcesses();
  65774. this._applyFilterValues();
  65775. this._light._markMeshesAsLightDirty();
  65776. },
  65777. enumerable: true,
  65778. configurable: true
  65779. });
  65780. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65781. /**
  65782. * Gets if the current filter is set to Poisson Sampling.
  65783. */
  65784. get: function () {
  65785. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65786. },
  65787. /**
  65788. * Sets the current filter to Poisson Sampling.
  65789. */
  65790. set: function (value) {
  65791. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65792. return;
  65793. }
  65794. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65795. },
  65796. enumerable: true,
  65797. configurable: true
  65798. });
  65799. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65800. /**
  65801. * Gets if the current filter is set to VSM.
  65802. * DEPRECATED. Should use useExponentialShadowMap instead.
  65803. */
  65804. get: function () {
  65805. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65806. return this.useExponentialShadowMap;
  65807. },
  65808. /**
  65809. * Sets the current filter is to VSM.
  65810. * DEPRECATED. Should use useExponentialShadowMap instead.
  65811. */
  65812. set: function (value) {
  65813. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65814. this.useExponentialShadowMap = value;
  65815. },
  65816. enumerable: true,
  65817. configurable: true
  65818. });
  65819. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65820. /**
  65821. * Gets if the current filter is set to blurred VSM.
  65822. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65823. */
  65824. get: function () {
  65825. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65826. return this.useBlurExponentialShadowMap;
  65827. },
  65828. /**
  65829. * Sets the current filter is to blurred VSM.
  65830. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65831. */
  65832. set: function (value) {
  65833. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65834. this.useBlurExponentialShadowMap = value;
  65835. },
  65836. enumerable: true,
  65837. configurable: true
  65838. });
  65839. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65840. /**
  65841. * Gets if the current filter is set to ESM.
  65842. */
  65843. get: function () {
  65844. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65845. },
  65846. /**
  65847. * Sets the current filter is to ESM.
  65848. */
  65849. set: function (value) {
  65850. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65851. return;
  65852. }
  65853. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65854. },
  65855. enumerable: true,
  65856. configurable: true
  65857. });
  65858. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65859. /**
  65860. * Gets if the current filter is set to filtered ESM.
  65861. */
  65862. get: function () {
  65863. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65864. },
  65865. /**
  65866. * Gets if the current filter is set to filtered ESM.
  65867. */
  65868. set: function (value) {
  65869. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65870. return;
  65871. }
  65872. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65873. },
  65874. enumerable: true,
  65875. configurable: true
  65876. });
  65877. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65878. /**
  65879. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65880. * exponential to prevent steep falloff artifacts).
  65881. */
  65882. get: function () {
  65883. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65884. },
  65885. /**
  65886. * Sets the current filter to "close ESM" (using the inverse of the
  65887. * exponential to prevent steep falloff artifacts).
  65888. */
  65889. set: function (value) {
  65890. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65891. return;
  65892. }
  65893. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65894. },
  65895. enumerable: true,
  65896. configurable: true
  65897. });
  65898. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65899. /**
  65900. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65901. * exponential to prevent steep falloff artifacts).
  65902. */
  65903. get: function () {
  65904. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65905. },
  65906. /**
  65907. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65908. * exponential to prevent steep falloff artifacts).
  65909. */
  65910. set: function (value) {
  65911. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65912. return;
  65913. }
  65914. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65915. },
  65916. enumerable: true,
  65917. configurable: true
  65918. });
  65919. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65920. /**
  65921. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65922. */
  65923. get: function () {
  65924. return this.filter === ShadowGenerator.FILTER_PCF;
  65925. },
  65926. /**
  65927. * Sets the current filter to "PCF" (percentage closer filtering).
  65928. */
  65929. set: function (value) {
  65930. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65931. return;
  65932. }
  65933. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65934. },
  65935. enumerable: true,
  65936. configurable: true
  65937. });
  65938. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65939. /**
  65940. * Gets the PCF or PCSS Quality.
  65941. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65942. */
  65943. get: function () {
  65944. return this._filteringQuality;
  65945. },
  65946. /**
  65947. * Sets the PCF or PCSS Quality.
  65948. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65949. */
  65950. set: function (filteringQuality) {
  65951. this._filteringQuality = filteringQuality;
  65952. },
  65953. enumerable: true,
  65954. configurable: true
  65955. });
  65956. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65957. /**
  65958. * Gets if the current filter is set to "PCSS" (contact hardening).
  65959. */
  65960. get: function () {
  65961. return this.filter === ShadowGenerator.FILTER_PCSS;
  65962. },
  65963. /**
  65964. * Sets the current filter to "PCSS" (contact hardening).
  65965. */
  65966. set: function (value) {
  65967. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65968. return;
  65969. }
  65970. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65971. },
  65972. enumerable: true,
  65973. configurable: true
  65974. });
  65975. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65976. /**
  65977. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65978. * Using a ratio helps keeping shape stability independently of the map size.
  65979. *
  65980. * It does not account for the light projection as it was having too much
  65981. * instability during the light setup or during light position changes.
  65982. *
  65983. * Only valid if useContactHardeningShadow is true.
  65984. */
  65985. get: function () {
  65986. return this._contactHardeningLightSizeUVRatio;
  65987. },
  65988. /**
  65989. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65990. * Using a ratio helps keeping shape stability independently of the map size.
  65991. *
  65992. * It does not account for the light projection as it was having too much
  65993. * instability during the light setup or during light position changes.
  65994. *
  65995. * Only valid if useContactHardeningShadow is true.
  65996. */
  65997. set: function (contactHardeningLightSizeUVRatio) {
  65998. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65999. },
  66000. enumerable: true,
  66001. configurable: true
  66002. });
  66003. /**
  66004. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66005. * 0 means strongest and 1 would means no shadow.
  66006. * @returns the darkness.
  66007. */
  66008. ShadowGenerator.prototype.getDarkness = function () {
  66009. return this._darkness;
  66010. };
  66011. /**
  66012. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66013. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66014. * @returns the shadow generator allowing fluent coding.
  66015. */
  66016. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66017. if (darkness >= 1.0)
  66018. this._darkness = 1.0;
  66019. else if (darkness <= 0.0)
  66020. this._darkness = 0.0;
  66021. else
  66022. this._darkness = darkness;
  66023. return this;
  66024. };
  66025. /**
  66026. * Sets the ability to have transparent shadow (boolean).
  66027. * @param transparent True if transparent else False
  66028. * @returns the shadow generator allowing fluent coding
  66029. */
  66030. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66031. this._transparencyShadow = transparent;
  66032. return this;
  66033. };
  66034. /**
  66035. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66036. * @returns The render target texture if present otherwise, null
  66037. */
  66038. ShadowGenerator.prototype.getShadowMap = function () {
  66039. return this._shadowMap;
  66040. };
  66041. /**
  66042. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66043. * @returns The render target texture if the shadow map is present otherwise, null
  66044. */
  66045. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66046. if (this._shadowMap2) {
  66047. return this._shadowMap2;
  66048. }
  66049. return this._shadowMap;
  66050. };
  66051. /**
  66052. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66053. * @param mesh Mesh to add
  66054. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66055. * @returns the Shadow Generator itself
  66056. */
  66057. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66058. if (includeDescendants === void 0) { includeDescendants = true; }
  66059. if (!this._shadowMap) {
  66060. return this;
  66061. }
  66062. if (!this._shadowMap.renderList) {
  66063. this._shadowMap.renderList = [];
  66064. }
  66065. this._shadowMap.renderList.push(mesh);
  66066. if (includeDescendants) {
  66067. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66068. }
  66069. return this;
  66070. var _a;
  66071. };
  66072. /**
  66073. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66074. * @param mesh Mesh to remove
  66075. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66076. * @returns the Shadow Generator itself
  66077. */
  66078. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66079. if (includeDescendants === void 0) { includeDescendants = true; }
  66080. if (!this._shadowMap || !this._shadowMap.renderList) {
  66081. return this;
  66082. }
  66083. var index = this._shadowMap.renderList.indexOf(mesh);
  66084. if (index !== -1) {
  66085. this._shadowMap.renderList.splice(index, 1);
  66086. }
  66087. if (includeDescendants) {
  66088. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66089. var child = _a[_i];
  66090. this.removeShadowCaster(child);
  66091. }
  66092. }
  66093. return this;
  66094. };
  66095. /**
  66096. * Returns the associated light object.
  66097. * @returns the light generating the shadow
  66098. */
  66099. ShadowGenerator.prototype.getLight = function () {
  66100. return this._light;
  66101. };
  66102. ShadowGenerator.prototype._initializeGenerator = function () {
  66103. this._light._markMeshesAsLightDirty();
  66104. this._initializeShadowMap();
  66105. };
  66106. ShadowGenerator.prototype._initializeShadowMap = function () {
  66107. var _this = this;
  66108. // Render target
  66109. var engine = this._scene.getEngine();
  66110. if (engine.webGLVersion > 1) {
  66111. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66112. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66113. }
  66114. else {
  66115. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66116. }
  66117. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66118. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66119. this._shadowMap.anisotropicFilteringLevel = 1;
  66120. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66121. this._shadowMap.renderParticles = false;
  66122. this._shadowMap.ignoreCameraViewport = true;
  66123. // Record Face Index before render.
  66124. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66125. _this._currentFaceIndex = faceIndex;
  66126. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66127. engine.setColorWrite(false);
  66128. }
  66129. });
  66130. // Custom render function.
  66131. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66132. // Blur if required afer render.
  66133. this._shadowMap.onAfterUnbindObservable.add(function () {
  66134. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66135. engine.setColorWrite(true);
  66136. }
  66137. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66138. return;
  66139. }
  66140. var shadowMap = _this.getShadowMapForRendering();
  66141. if (shadowMap) {
  66142. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66143. }
  66144. });
  66145. // Clear according to the chosen filter.
  66146. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66147. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66148. this._shadowMap.onClearObservable.add(function (engine) {
  66149. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66150. engine.clear(clearOne, false, true, false);
  66151. }
  66152. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66153. engine.clear(clearZero, true, true, false);
  66154. }
  66155. else {
  66156. engine.clear(clearOne, true, true, false);
  66157. }
  66158. });
  66159. };
  66160. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66161. var _this = this;
  66162. var engine = this._scene.getEngine();
  66163. var targetSize = this._mapSize / this.blurScale;
  66164. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66165. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66166. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66167. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66168. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66169. }
  66170. if (this.useKernelBlur) {
  66171. 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);
  66172. this._kernelBlurXPostprocess.width = targetSize;
  66173. this._kernelBlurXPostprocess.height = targetSize;
  66174. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66175. effect.setTexture("textureSampler", _this._shadowMap);
  66176. });
  66177. 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);
  66178. this._kernelBlurXPostprocess.autoClear = false;
  66179. this._kernelBlurYPostprocess.autoClear = false;
  66180. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66181. this._kernelBlurXPostprocess.packedFloat = true;
  66182. this._kernelBlurYPostprocess.packedFloat = true;
  66183. }
  66184. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66185. }
  66186. else {
  66187. 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);
  66188. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66189. effect.setFloat2("screenSize", targetSize, targetSize);
  66190. effect.setTexture("textureSampler", _this._shadowMap);
  66191. });
  66192. this._boxBlurPostprocess.autoClear = false;
  66193. this._blurPostProcesses = [this._boxBlurPostprocess];
  66194. }
  66195. };
  66196. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66197. var index;
  66198. var engine = this._scene.getEngine();
  66199. if (depthOnlySubMeshes.length) {
  66200. engine.setColorWrite(false);
  66201. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66202. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66203. }
  66204. engine.setColorWrite(true);
  66205. }
  66206. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66207. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66208. }
  66209. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66210. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66211. }
  66212. if (this._transparencyShadow) {
  66213. for (index = 0; index < transparentSubMeshes.length; index++) {
  66214. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66215. }
  66216. }
  66217. };
  66218. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66219. var _this = this;
  66220. var mesh = subMesh.getRenderingMesh();
  66221. var scene = this._scene;
  66222. var engine = scene.getEngine();
  66223. var material = subMesh.getMaterial();
  66224. if (!material) {
  66225. return;
  66226. }
  66227. // Culling
  66228. engine.setState(material.backFaceCulling);
  66229. // Managing instances
  66230. var batch = mesh._getInstancesRenderList(subMesh._id);
  66231. if (batch.mustReturn) {
  66232. return;
  66233. }
  66234. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66235. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66236. engine.enableEffect(this._effect);
  66237. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66238. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66239. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66240. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66241. this._effect.setVector3("lightData", this._cachedDirection);
  66242. }
  66243. else {
  66244. this._effect.setVector3("lightData", this._cachedPosition);
  66245. }
  66246. if (scene.activeCamera) {
  66247. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66248. }
  66249. // Alpha test
  66250. if (material && material.needAlphaTesting()) {
  66251. var alphaTexture = material.getAlphaTestTexture();
  66252. if (alphaTexture) {
  66253. this._effect.setTexture("diffuseSampler", alphaTexture);
  66254. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66255. }
  66256. }
  66257. // Bones
  66258. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66259. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66260. }
  66261. // Morph targets
  66262. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66263. if (this.forceBackFacesOnly) {
  66264. engine.setState(true, 0, false, true);
  66265. }
  66266. // Draw
  66267. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66268. if (this.forceBackFacesOnly) {
  66269. engine.setState(true, 0, false, false);
  66270. }
  66271. }
  66272. else {
  66273. // Need to reset refresh rate of the shadowMap
  66274. if (this._shadowMap) {
  66275. this._shadowMap.resetRefreshCounter();
  66276. }
  66277. }
  66278. };
  66279. ShadowGenerator.prototype._applyFilterValues = function () {
  66280. if (!this._shadowMap) {
  66281. return;
  66282. }
  66283. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66284. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66285. }
  66286. else {
  66287. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66288. }
  66289. };
  66290. /**
  66291. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66292. * @param onCompiled Callback triggered at the and of the effects compilation
  66293. * @param options Sets of optional options forcing the compilation with different modes
  66294. */
  66295. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66296. var _this = this;
  66297. var localOptions = __assign({ useInstances: false }, options);
  66298. var shadowMap = this.getShadowMap();
  66299. if (!shadowMap) {
  66300. if (onCompiled) {
  66301. onCompiled(this);
  66302. }
  66303. return;
  66304. }
  66305. var renderList = shadowMap.renderList;
  66306. if (!renderList) {
  66307. if (onCompiled) {
  66308. onCompiled(this);
  66309. }
  66310. return;
  66311. }
  66312. var subMeshes = new Array();
  66313. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66314. var mesh = renderList_1[_i];
  66315. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66316. }
  66317. if (subMeshes.length === 0) {
  66318. if (onCompiled) {
  66319. onCompiled(this);
  66320. }
  66321. return;
  66322. }
  66323. var currentIndex = 0;
  66324. var checkReady = function () {
  66325. if (!_this._scene || !_this._scene.getEngine()) {
  66326. return;
  66327. }
  66328. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66329. currentIndex++;
  66330. if (currentIndex >= subMeshes.length) {
  66331. if (onCompiled) {
  66332. onCompiled(_this);
  66333. }
  66334. return;
  66335. }
  66336. }
  66337. setTimeout(checkReady, 16);
  66338. };
  66339. checkReady();
  66340. };
  66341. /**
  66342. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66343. * @param options Sets of optional options forcing the compilation with different modes
  66344. * @returns A promise that resolves when the compilation completes
  66345. */
  66346. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66347. var _this = this;
  66348. return new Promise(function (resolve) {
  66349. _this.forceCompilation(function () {
  66350. resolve();
  66351. }, options);
  66352. });
  66353. };
  66354. /**
  66355. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66356. * @param subMesh The submesh we want to render in the shadow map
  66357. * @param useInstances Defines wether will draw in the map using instances
  66358. * @returns true if ready otherwise, false
  66359. */
  66360. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66361. var defines = [];
  66362. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66363. defines.push("#define FLOAT");
  66364. }
  66365. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66366. defines.push("#define ESM");
  66367. }
  66368. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66369. defines.push("#define DEPTHTEXTURE");
  66370. }
  66371. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66372. var mesh = subMesh.getMesh();
  66373. var material = subMesh.getMaterial();
  66374. // Normal bias.
  66375. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66376. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66377. defines.push("#define NORMAL");
  66378. if (mesh.nonUniformScaling) {
  66379. defines.push("#define NONUNIFORMSCALING");
  66380. }
  66381. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66382. defines.push("#define DIRECTIONINLIGHTDATA");
  66383. }
  66384. }
  66385. // Alpha test
  66386. if (material && material.needAlphaTesting()) {
  66387. var alphaTexture = material.getAlphaTestTexture();
  66388. if (alphaTexture) {
  66389. defines.push("#define ALPHATEST");
  66390. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66391. attribs.push(BABYLON.VertexBuffer.UVKind);
  66392. defines.push("#define UV1");
  66393. }
  66394. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66395. if (alphaTexture.coordinatesIndex === 1) {
  66396. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66397. defines.push("#define UV2");
  66398. }
  66399. }
  66400. }
  66401. }
  66402. // Bones
  66403. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66404. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66405. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66406. if (mesh.numBoneInfluencers > 4) {
  66407. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66408. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66409. }
  66410. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66411. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66412. }
  66413. else {
  66414. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66415. }
  66416. // Morph targets
  66417. var manager = mesh.morphTargetManager;
  66418. var morphInfluencers = 0;
  66419. if (manager) {
  66420. if (manager.numInfluencers > 0) {
  66421. defines.push("#define MORPHTARGETS");
  66422. morphInfluencers = manager.numInfluencers;
  66423. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66424. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66425. }
  66426. }
  66427. // Instances
  66428. if (useInstances) {
  66429. defines.push("#define INSTANCES");
  66430. attribs.push("world0");
  66431. attribs.push("world1");
  66432. attribs.push("world2");
  66433. attribs.push("world3");
  66434. }
  66435. // Get correct effect
  66436. var join = defines.join("\n");
  66437. if (this._cachedDefines !== join) {
  66438. this._cachedDefines = join;
  66439. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66440. }
  66441. if (!this._effect.isReady()) {
  66442. return false;
  66443. }
  66444. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66445. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66446. this._initializeBlurRTTAndPostProcesses();
  66447. }
  66448. }
  66449. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66450. return false;
  66451. }
  66452. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66453. return false;
  66454. }
  66455. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66456. return false;
  66457. }
  66458. return true;
  66459. };
  66460. /**
  66461. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66462. * @param defines Defines of the material we want to update
  66463. * @param lightIndex Index of the light in the enabled light list of the material
  66464. */
  66465. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66466. var scene = this._scene;
  66467. var light = this._light;
  66468. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66469. return;
  66470. }
  66471. defines["SHADOW" + lightIndex] = true;
  66472. if (this.useContactHardeningShadow) {
  66473. defines["SHADOWPCSS" + lightIndex] = true;
  66474. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66475. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66476. }
  66477. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66478. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66479. }
  66480. // else default to high.
  66481. }
  66482. if (this.usePercentageCloserFiltering) {
  66483. defines["SHADOWPCF" + lightIndex] = true;
  66484. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66485. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66486. }
  66487. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66488. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66489. }
  66490. // else default to high.
  66491. }
  66492. else if (this.usePoissonSampling) {
  66493. defines["SHADOWPOISSON" + lightIndex] = true;
  66494. }
  66495. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66496. defines["SHADOWESM" + lightIndex] = true;
  66497. }
  66498. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66499. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66500. }
  66501. if (light.needCube()) {
  66502. defines["SHADOWCUBE" + lightIndex] = true;
  66503. }
  66504. };
  66505. /**
  66506. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66507. * defined in the generator but impacting the effect).
  66508. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66509. * @param effect The effect we are binfing the information for
  66510. */
  66511. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66512. var light = this._light;
  66513. var scene = this._scene;
  66514. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66515. return;
  66516. }
  66517. var camera = scene.activeCamera;
  66518. if (!camera) {
  66519. return;
  66520. }
  66521. var shadowMap = this.getShadowMap();
  66522. if (!shadowMap) {
  66523. return;
  66524. }
  66525. if (!light.needCube()) {
  66526. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66527. }
  66528. // Only PCF uses depth stencil texture.
  66529. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66530. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66531. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66532. }
  66533. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66534. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66535. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66536. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66537. }
  66538. else {
  66539. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66540. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66541. }
  66542. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66543. };
  66544. /**
  66545. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66546. * (eq to shadow prjection matrix * light transform matrix)
  66547. * @returns The transform matrix used to create the shadow map
  66548. */
  66549. ShadowGenerator.prototype.getTransformMatrix = function () {
  66550. var scene = this._scene;
  66551. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66552. return this._transformMatrix;
  66553. }
  66554. this._currentRenderID = scene.getRenderId();
  66555. this._currentFaceIndexCache = this._currentFaceIndex;
  66556. var lightPosition = this._light.position;
  66557. if (this._light.computeTransformedInformation()) {
  66558. lightPosition = this._light.transformedPosition;
  66559. }
  66560. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66561. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66562. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66563. }
  66564. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66565. this._cachedPosition.copyFrom(lightPosition);
  66566. this._cachedDirection.copyFrom(this._lightDirection);
  66567. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66568. var shadowMap = this.getShadowMap();
  66569. if (shadowMap) {
  66570. var renderList = shadowMap.renderList;
  66571. if (renderList) {
  66572. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66573. }
  66574. }
  66575. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66576. }
  66577. return this._transformMatrix;
  66578. };
  66579. /**
  66580. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66581. * Cube and 2D textures for instance.
  66582. */
  66583. ShadowGenerator.prototype.recreateShadowMap = function () {
  66584. var shadowMap = this._shadowMap;
  66585. if (!shadowMap) {
  66586. return;
  66587. }
  66588. // Track render list.
  66589. var renderList = shadowMap.renderList;
  66590. // Clean up existing data.
  66591. this._disposeRTTandPostProcesses();
  66592. // Reinitializes.
  66593. this._initializeGenerator();
  66594. // Reaffect the filter to ensure a correct fallback if necessary.
  66595. this.filter = this.filter;
  66596. // Reaffect the filter.
  66597. this._applyFilterValues();
  66598. // Reaffect Render List.
  66599. this._shadowMap.renderList = renderList;
  66600. };
  66601. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66602. if (this._shadowMap2) {
  66603. this._shadowMap2.dispose();
  66604. this._shadowMap2 = null;
  66605. }
  66606. if (this._boxBlurPostprocess) {
  66607. this._boxBlurPostprocess.dispose();
  66608. this._boxBlurPostprocess = null;
  66609. }
  66610. if (this._kernelBlurXPostprocess) {
  66611. this._kernelBlurXPostprocess.dispose();
  66612. this._kernelBlurXPostprocess = null;
  66613. }
  66614. if (this._kernelBlurYPostprocess) {
  66615. this._kernelBlurYPostprocess.dispose();
  66616. this._kernelBlurYPostprocess = null;
  66617. }
  66618. this._blurPostProcesses = [];
  66619. };
  66620. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66621. if (this._shadowMap) {
  66622. this._shadowMap.dispose();
  66623. this._shadowMap = null;
  66624. }
  66625. this._disposeBlurPostProcesses();
  66626. };
  66627. /**
  66628. * Disposes the ShadowGenerator.
  66629. * Returns nothing.
  66630. */
  66631. ShadowGenerator.prototype.dispose = function () {
  66632. this._disposeRTTandPostProcesses();
  66633. if (this._light) {
  66634. this._light._shadowGenerator = null;
  66635. this._light._markMeshesAsLightDirty();
  66636. }
  66637. };
  66638. /**
  66639. * Serializes the shadow generator setup to a json object.
  66640. * @returns The serialized JSON object
  66641. */
  66642. ShadowGenerator.prototype.serialize = function () {
  66643. var serializationObject = {};
  66644. var shadowMap = this.getShadowMap();
  66645. if (!shadowMap) {
  66646. return serializationObject;
  66647. }
  66648. serializationObject.lightId = this._light.id;
  66649. serializationObject.mapSize = shadowMap.getRenderSize();
  66650. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66651. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66652. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66653. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66654. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66655. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66656. serializationObject.depthScale = this.depthScale;
  66657. serializationObject.darkness = this.getDarkness();
  66658. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66659. serializationObject.blurKernel = this.blurKernel;
  66660. serializationObject.blurScale = this.blurScale;
  66661. serializationObject.useKernelBlur = this.useKernelBlur;
  66662. serializationObject.transparencyShadow = this._transparencyShadow;
  66663. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  66664. serializationObject.bias = this.bias;
  66665. serializationObject.normalBias = this.normalBias;
  66666. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66667. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66668. serializationObject.filteringQuality = this.filteringQuality;
  66669. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66670. serializationObject.renderList = [];
  66671. if (shadowMap.renderList) {
  66672. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66673. var mesh = shadowMap.renderList[meshIndex];
  66674. serializationObject.renderList.push(mesh.id);
  66675. }
  66676. }
  66677. return serializationObject;
  66678. };
  66679. /**
  66680. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66681. * @param parsedShadowGenerator The JSON object to parse
  66682. * @param scene The scene to create the shadow map for
  66683. * @returns The parsed shadow generator
  66684. */
  66685. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66686. //casting to point light, as light is missing the position attr and typescript complains.
  66687. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66688. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66689. var shadowMap = shadowGenerator.getShadowMap();
  66690. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66691. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66692. meshes.forEach(function (mesh) {
  66693. if (!shadowMap) {
  66694. return;
  66695. }
  66696. if (!shadowMap.renderList) {
  66697. shadowMap.renderList = [];
  66698. }
  66699. shadowMap.renderList.push(mesh);
  66700. });
  66701. }
  66702. if (parsedShadowGenerator.usePoissonSampling) {
  66703. shadowGenerator.usePoissonSampling = true;
  66704. }
  66705. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66706. shadowGenerator.useExponentialShadowMap = true;
  66707. }
  66708. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66709. shadowGenerator.useBlurExponentialShadowMap = true;
  66710. }
  66711. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66712. shadowGenerator.useCloseExponentialShadowMap = true;
  66713. }
  66714. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66715. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66716. }
  66717. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66718. shadowGenerator.usePercentageCloserFiltering = true;
  66719. }
  66720. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66721. shadowGenerator.useContactHardeningShadow = true;
  66722. }
  66723. if (parsedShadowGenerator.filteringQuality) {
  66724. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66725. }
  66726. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66727. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66728. }
  66729. // Backward compat
  66730. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66731. shadowGenerator.useExponentialShadowMap = true;
  66732. }
  66733. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66734. shadowGenerator.useBlurExponentialShadowMap = true;
  66735. }
  66736. if (parsedShadowGenerator.depthScale) {
  66737. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66738. }
  66739. if (parsedShadowGenerator.blurScale) {
  66740. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66741. }
  66742. if (parsedShadowGenerator.blurBoxOffset) {
  66743. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66744. }
  66745. if (parsedShadowGenerator.useKernelBlur) {
  66746. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66747. }
  66748. if (parsedShadowGenerator.blurKernel) {
  66749. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66750. }
  66751. if (parsedShadowGenerator.bias !== undefined) {
  66752. shadowGenerator.bias = parsedShadowGenerator.bias;
  66753. }
  66754. if (parsedShadowGenerator.normalBias !== undefined) {
  66755. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66756. }
  66757. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  66758. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  66759. }
  66760. if (parsedShadowGenerator.darkness) {
  66761. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66762. }
  66763. if (parsedShadowGenerator.transparencyShadow) {
  66764. shadowGenerator.setTransparencyShadow(true);
  66765. }
  66766. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66767. return shadowGenerator;
  66768. };
  66769. /**
  66770. * Shadow generator mode None: no filtering applied.
  66771. */
  66772. ShadowGenerator.FILTER_NONE = 0;
  66773. /**
  66774. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66775. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66776. */
  66777. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66778. /**
  66779. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66780. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66781. */
  66782. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66783. /**
  66784. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66785. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66786. */
  66787. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66788. /**
  66789. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66790. * edge artifacts on steep falloff.
  66791. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66792. */
  66793. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66794. /**
  66795. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66796. * edge artifacts on steep falloff.
  66797. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66798. */
  66799. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66800. /**
  66801. * Shadow generator mode PCF: Percentage Closer Filtering
  66802. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66803. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66804. */
  66805. ShadowGenerator.FILTER_PCF = 6;
  66806. /**
  66807. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66808. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66809. * Contact Hardening
  66810. */
  66811. ShadowGenerator.FILTER_PCSS = 7;
  66812. /**
  66813. * Reserved for PCF and PCSS
  66814. * Highest Quality.
  66815. *
  66816. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66817. *
  66818. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66819. */
  66820. ShadowGenerator.QUALITY_HIGH = 0;
  66821. /**
  66822. * Reserved for PCF and PCSS
  66823. * Good tradeoff for quality/perf cross devices
  66824. *
  66825. * Execute PCF on a 3*3 kernel.
  66826. *
  66827. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66828. */
  66829. ShadowGenerator.QUALITY_MEDIUM = 1;
  66830. /**
  66831. * Reserved for PCF and PCSS
  66832. * The lowest quality but the fastest.
  66833. *
  66834. * Execute PCF on a 1*1 kernel.
  66835. *
  66836. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66837. */
  66838. ShadowGenerator.QUALITY_LOW = 2;
  66839. return ShadowGenerator;
  66840. }());
  66841. BABYLON.ShadowGenerator = ShadowGenerator;
  66842. })(BABYLON || (BABYLON = {}));
  66843. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66844. var BABYLON;
  66845. (function (BABYLON) {
  66846. var DefaultLoadingScreen = /** @class */ (function () {
  66847. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66848. if (_loadingText === void 0) { _loadingText = ""; }
  66849. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66850. var _this = this;
  66851. this._renderingCanvas = _renderingCanvas;
  66852. this._loadingText = _loadingText;
  66853. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66854. // Resize
  66855. this._resizeLoadingUI = function () {
  66856. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66857. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66858. if (!_this._loadingDiv) {
  66859. return;
  66860. }
  66861. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66862. _this._loadingDiv.style.left = canvasRect.left + "px";
  66863. _this._loadingDiv.style.top = canvasRect.top + "px";
  66864. _this._loadingDiv.style.width = canvasRect.width + "px";
  66865. _this._loadingDiv.style.height = canvasRect.height + "px";
  66866. };
  66867. }
  66868. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66869. if (this._loadingDiv) {
  66870. // Do not add a loading screen if there is already one
  66871. return;
  66872. }
  66873. this._loadingDiv = document.createElement("div");
  66874. this._loadingDiv.id = "babylonjsLoadingDiv";
  66875. this._loadingDiv.style.opacity = "0";
  66876. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66877. this._loadingDiv.style.pointerEvents = "none";
  66878. // Loading text
  66879. this._loadingTextDiv = document.createElement("div");
  66880. this._loadingTextDiv.style.position = "absolute";
  66881. this._loadingTextDiv.style.left = "0";
  66882. this._loadingTextDiv.style.top = "50%";
  66883. this._loadingTextDiv.style.marginTop = "80px";
  66884. this._loadingTextDiv.style.width = "100%";
  66885. this._loadingTextDiv.style.height = "20px";
  66886. this._loadingTextDiv.style.fontFamily = "Arial";
  66887. this._loadingTextDiv.style.fontSize = "14px";
  66888. this._loadingTextDiv.style.color = "white";
  66889. this._loadingTextDiv.style.textAlign = "center";
  66890. this._loadingTextDiv.innerHTML = "Loading";
  66891. this._loadingDiv.appendChild(this._loadingTextDiv);
  66892. //set the predefined text
  66893. this._loadingTextDiv.innerHTML = this._loadingText;
  66894. // Generating keyframes
  66895. var style = document.createElement('style');
  66896. style.type = 'text/css';
  66897. 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 }";
  66898. style.innerHTML = keyFrames;
  66899. document.getElementsByTagName('head')[0].appendChild(style);
  66900. // Loading img
  66901. var imgBack = new Image();
  66902. 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";
  66903. imgBack.style.position = "absolute";
  66904. imgBack.style.left = "50%";
  66905. imgBack.style.top = "50%";
  66906. imgBack.style.marginLeft = "-60px";
  66907. imgBack.style.marginTop = "-60px";
  66908. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66909. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66910. imgBack.style.transformOrigin = "50% 50%";
  66911. imgBack.style.webkitTransformOrigin = "50% 50%";
  66912. this._loadingDiv.appendChild(imgBack);
  66913. this._resizeLoadingUI();
  66914. window.addEventListener("resize", this._resizeLoadingUI);
  66915. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66916. document.body.appendChild(this._loadingDiv);
  66917. this._loadingDiv.style.opacity = "1";
  66918. };
  66919. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66920. var _this = this;
  66921. if (!this._loadingDiv) {
  66922. return;
  66923. }
  66924. var onTransitionEnd = function () {
  66925. if (!_this._loadingDiv) {
  66926. return;
  66927. }
  66928. document.body.removeChild(_this._loadingDiv);
  66929. window.removeEventListener("resize", _this._resizeLoadingUI);
  66930. _this._loadingDiv = null;
  66931. };
  66932. this._loadingDiv.style.opacity = "0";
  66933. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66934. };
  66935. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66936. set: function (text) {
  66937. this._loadingText = text;
  66938. if (this._loadingTextDiv) {
  66939. this._loadingTextDiv.innerHTML = this._loadingText;
  66940. }
  66941. },
  66942. enumerable: true,
  66943. configurable: true
  66944. });
  66945. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66946. get: function () {
  66947. return this._loadingDivBackgroundColor;
  66948. },
  66949. set: function (color) {
  66950. this._loadingDivBackgroundColor = color;
  66951. if (!this._loadingDiv) {
  66952. return;
  66953. }
  66954. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66955. },
  66956. enumerable: true,
  66957. configurable: true
  66958. });
  66959. return DefaultLoadingScreen;
  66960. }());
  66961. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66962. })(BABYLON || (BABYLON = {}));
  66963. //# sourceMappingURL=babylon.loadingScreen.js.map
  66964. var BABYLON;
  66965. (function (BABYLON) {
  66966. var SceneLoaderProgressEvent = /** @class */ (function () {
  66967. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66968. this.lengthComputable = lengthComputable;
  66969. this.loaded = loaded;
  66970. this.total = total;
  66971. }
  66972. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66973. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66974. };
  66975. return SceneLoaderProgressEvent;
  66976. }());
  66977. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66978. var SceneLoader = /** @class */ (function () {
  66979. function SceneLoader() {
  66980. }
  66981. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66982. get: function () {
  66983. return 0;
  66984. },
  66985. enumerable: true,
  66986. configurable: true
  66987. });
  66988. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66989. get: function () {
  66990. return 1;
  66991. },
  66992. enumerable: true,
  66993. configurable: true
  66994. });
  66995. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66996. get: function () {
  66997. return 2;
  66998. },
  66999. enumerable: true,
  67000. configurable: true
  67001. });
  67002. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67003. get: function () {
  67004. return 3;
  67005. },
  67006. enumerable: true,
  67007. configurable: true
  67008. });
  67009. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67010. get: function () {
  67011. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67012. },
  67013. set: function (value) {
  67014. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67015. },
  67016. enumerable: true,
  67017. configurable: true
  67018. });
  67019. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67020. get: function () {
  67021. return SceneLoader._ShowLoadingScreen;
  67022. },
  67023. set: function (value) {
  67024. SceneLoader._ShowLoadingScreen = value;
  67025. },
  67026. enumerable: true,
  67027. configurable: true
  67028. });
  67029. Object.defineProperty(SceneLoader, "loggingLevel", {
  67030. get: function () {
  67031. return SceneLoader._loggingLevel;
  67032. },
  67033. set: function (value) {
  67034. SceneLoader._loggingLevel = value;
  67035. },
  67036. enumerable: true,
  67037. configurable: true
  67038. });
  67039. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67040. get: function () {
  67041. return SceneLoader._CleanBoneMatrixWeights;
  67042. },
  67043. set: function (value) {
  67044. SceneLoader._CleanBoneMatrixWeights = value;
  67045. },
  67046. enumerable: true,
  67047. configurable: true
  67048. });
  67049. SceneLoader._getDefaultPlugin = function () {
  67050. return SceneLoader._registeredPlugins[".babylon"];
  67051. };
  67052. SceneLoader._getPluginForExtension = function (extension) {
  67053. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67054. if (registeredPlugin) {
  67055. return registeredPlugin;
  67056. }
  67057. 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");
  67058. return SceneLoader._getDefaultPlugin();
  67059. };
  67060. SceneLoader._getPluginForDirectLoad = function (data) {
  67061. for (var extension in SceneLoader._registeredPlugins) {
  67062. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67063. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67064. return SceneLoader._registeredPlugins[extension];
  67065. }
  67066. }
  67067. return SceneLoader._getDefaultPlugin();
  67068. };
  67069. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67070. if (sceneFilename.name) {
  67071. sceneFilename = sceneFilename.name;
  67072. }
  67073. var queryStringPosition = sceneFilename.indexOf("?");
  67074. if (queryStringPosition !== -1) {
  67075. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67076. }
  67077. var dotPosition = sceneFilename.lastIndexOf(".");
  67078. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67079. return SceneLoader._getPluginForExtension(extension);
  67080. };
  67081. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67082. SceneLoader._getDirectLoad = function (sceneFilename) {
  67083. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67084. return sceneFilename.substr(5);
  67085. }
  67086. return null;
  67087. };
  67088. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67089. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67090. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67091. var plugin;
  67092. if (registeredPlugin.plugin.createPlugin) {
  67093. plugin = registeredPlugin.plugin.createPlugin();
  67094. }
  67095. else {
  67096. plugin = registeredPlugin.plugin;
  67097. }
  67098. var useArrayBuffer = registeredPlugin.isBinary;
  67099. var database;
  67100. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67101. var dataCallback = function (data, responseURL) {
  67102. if (scene.isDisposed) {
  67103. onError("Scene has been disposed");
  67104. return;
  67105. }
  67106. scene.database = database;
  67107. onSuccess(plugin, data, responseURL);
  67108. };
  67109. var request = null;
  67110. var pluginDisposed = false;
  67111. var onDisposeObservable = plugin.onDisposeObservable;
  67112. if (onDisposeObservable) {
  67113. onDisposeObservable.add(function () {
  67114. pluginDisposed = true;
  67115. if (request) {
  67116. request.abort();
  67117. request = null;
  67118. }
  67119. onDispose();
  67120. });
  67121. }
  67122. var manifestChecked = function () {
  67123. if (pluginDisposed) {
  67124. return;
  67125. }
  67126. var url = rootUrl + sceneFilename;
  67127. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67128. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67129. } : undefined, database, useArrayBuffer, function (request, exception) {
  67130. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67131. });
  67132. };
  67133. if (directLoad) {
  67134. dataCallback(directLoad);
  67135. return plugin;
  67136. }
  67137. if (rootUrl.indexOf("file:") === -1) {
  67138. var engine = scene.getEngine();
  67139. var canUseOfflineSupport = engine.enableOfflineSupport;
  67140. if (canUseOfflineSupport) {
  67141. // Also check for exceptions
  67142. var exceptionFound = false;
  67143. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67144. var regex = _a[_i];
  67145. if (regex.test(rootUrl + sceneFilename)) {
  67146. exceptionFound = true;
  67147. break;
  67148. }
  67149. }
  67150. canUseOfflineSupport = !exceptionFound;
  67151. }
  67152. if (canUseOfflineSupport) {
  67153. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67154. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67155. }
  67156. else {
  67157. manifestChecked();
  67158. }
  67159. }
  67160. // Loading file from disk via input file or drag'n'drop
  67161. else {
  67162. var fileOrString = sceneFilename;
  67163. if (fileOrString.name) { // File
  67164. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67165. }
  67166. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67167. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67168. }
  67169. else {
  67170. onError("Unable to find file named " + sceneFilename);
  67171. }
  67172. }
  67173. return plugin;
  67174. };
  67175. // Public functions
  67176. SceneLoader.GetPluginForExtension = function (extension) {
  67177. return SceneLoader._getPluginForExtension(extension).plugin;
  67178. };
  67179. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67180. return !!SceneLoader._registeredPlugins[extension];
  67181. };
  67182. SceneLoader.RegisterPlugin = function (plugin) {
  67183. if (typeof plugin.extensions === "string") {
  67184. var extension = plugin.extensions;
  67185. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67186. plugin: plugin,
  67187. isBinary: false
  67188. };
  67189. }
  67190. else {
  67191. var extensions = plugin.extensions;
  67192. Object.keys(extensions).forEach(function (extension) {
  67193. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67194. plugin: plugin,
  67195. isBinary: extensions[extension].isBinary
  67196. };
  67197. });
  67198. }
  67199. };
  67200. /**
  67201. * Import meshes into a scene
  67202. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67203. * @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)
  67204. * @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)
  67205. * @param scene the instance of BABYLON.Scene to append to
  67206. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67207. * @param onProgress a callback with a progress event for each file being loaded
  67208. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67209. * @param pluginExtension the extension used to determine the plugin
  67210. * @returns The loaded plugin
  67211. */
  67212. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67213. if (sceneFilename === void 0) { sceneFilename = ""; }
  67214. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67215. if (onSuccess === void 0) { onSuccess = null; }
  67216. if (onProgress === void 0) { onProgress = null; }
  67217. if (onError === void 0) { onError = null; }
  67218. if (pluginExtension === void 0) { pluginExtension = null; }
  67219. if (!scene) {
  67220. BABYLON.Tools.Error("No scene available to import mesh to");
  67221. return null;
  67222. }
  67223. if (!sceneFilename) {
  67224. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67225. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67226. }
  67227. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67228. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67229. return null;
  67230. }
  67231. var loadingToken = {};
  67232. scene._addPendingData(loadingToken);
  67233. var disposeHandler = function () {
  67234. scene._removePendingData(loadingToken);
  67235. };
  67236. var errorHandler = function (message, exception) {
  67237. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67238. if (onError) {
  67239. onError(scene, errorMessage, exception);
  67240. }
  67241. else {
  67242. BABYLON.Tools.Error(errorMessage);
  67243. // should the exception be thrown?
  67244. }
  67245. disposeHandler();
  67246. };
  67247. var progressHandler = onProgress ? function (event) {
  67248. try {
  67249. onProgress(event);
  67250. }
  67251. catch (e) {
  67252. errorHandler("Error in onProgress callback", e);
  67253. }
  67254. } : undefined;
  67255. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67256. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67257. if (onSuccess) {
  67258. try {
  67259. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67260. }
  67261. catch (e) {
  67262. errorHandler("Error in onSuccess callback", e);
  67263. }
  67264. }
  67265. scene._removePendingData(loadingToken);
  67266. };
  67267. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67268. if (plugin.rewriteRootURL) {
  67269. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67270. }
  67271. if (sceneFilename === "") {
  67272. if (sceneFilename === "") {
  67273. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67274. }
  67275. }
  67276. if (plugin.importMesh) {
  67277. var syncedPlugin = plugin;
  67278. var meshes = new Array();
  67279. var particleSystems = new Array();
  67280. var skeletons = new Array();
  67281. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67282. return;
  67283. }
  67284. scene.loadingPluginName = plugin.name;
  67285. successHandler(meshes, particleSystems, skeletons, []);
  67286. }
  67287. else {
  67288. var asyncedPlugin = plugin;
  67289. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67290. scene.loadingPluginName = plugin.name;
  67291. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67292. }).catch(function (error) {
  67293. errorHandler(error.message, error);
  67294. });
  67295. }
  67296. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67297. };
  67298. /**
  67299. * Import meshes into a scene
  67300. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67301. * @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)
  67302. * @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)
  67303. * @param scene the instance of BABYLON.Scene to append to
  67304. * @param onProgress a callback with a progress event for each file being loaded
  67305. * @param pluginExtension the extension used to determine the plugin
  67306. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67307. */
  67308. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67309. if (sceneFilename === void 0) { sceneFilename = ""; }
  67310. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67311. if (onProgress === void 0) { onProgress = null; }
  67312. if (pluginExtension === void 0) { pluginExtension = null; }
  67313. return new Promise(function (resolve, reject) {
  67314. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67315. resolve({
  67316. meshes: meshes,
  67317. particleSystems: particleSystems,
  67318. skeletons: skeletons,
  67319. animationGroups: animationGroups
  67320. });
  67321. }, onProgress, function (scene, message, exception) {
  67322. reject(exception || new Error(message));
  67323. }, pluginExtension);
  67324. });
  67325. };
  67326. /**
  67327. * Load a scene
  67328. * @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)
  67329. * @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)
  67330. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67331. * @param onSuccess a callback with the scene when import succeeds
  67332. * @param onProgress a callback with a progress event for each file being loaded
  67333. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67334. * @param pluginExtension the extension used to determine the plugin
  67335. * @returns The loaded plugin
  67336. */
  67337. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67338. if (onSuccess === void 0) { onSuccess = null; }
  67339. if (onProgress === void 0) { onProgress = null; }
  67340. if (onError === void 0) { onError = null; }
  67341. if (pluginExtension === void 0) { pluginExtension = null; }
  67342. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67343. };
  67344. /**
  67345. * Load a scene
  67346. * @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)
  67347. * @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)
  67348. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67349. * @param onProgress a callback with a progress event for each file being loaded
  67350. * @param pluginExtension the extension used to determine the plugin
  67351. * @returns The loaded scene
  67352. */
  67353. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67354. if (onProgress === void 0) { onProgress = null; }
  67355. if (pluginExtension === void 0) { pluginExtension = null; }
  67356. return new Promise(function (resolve, reject) {
  67357. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67358. resolve(scene);
  67359. }, onProgress, function (scene, message, exception) {
  67360. reject(exception || new Error(message));
  67361. }, pluginExtension);
  67362. });
  67363. };
  67364. /**
  67365. * Append a scene
  67366. * @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)
  67367. * @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)
  67368. * @param scene is the instance of BABYLON.Scene to append to
  67369. * @param onSuccess a callback with the scene when import succeeds
  67370. * @param onProgress a callback with a progress event for each file being loaded
  67371. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67372. * @param pluginExtension the extension used to determine the plugin
  67373. * @returns The loaded plugin
  67374. */
  67375. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67376. if (sceneFilename === void 0) { sceneFilename = ""; }
  67377. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67378. if (onSuccess === void 0) { onSuccess = null; }
  67379. if (onProgress === void 0) { onProgress = null; }
  67380. if (onError === void 0) { onError = null; }
  67381. if (pluginExtension === void 0) { pluginExtension = null; }
  67382. if (!scene) {
  67383. BABYLON.Tools.Error("No scene available to append to");
  67384. return null;
  67385. }
  67386. if (!sceneFilename) {
  67387. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67388. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67389. }
  67390. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67391. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67392. return null;
  67393. }
  67394. if (SceneLoader.ShowLoadingScreen) {
  67395. scene.getEngine().displayLoadingUI();
  67396. }
  67397. var loadingToken = {};
  67398. scene._addPendingData(loadingToken);
  67399. var disposeHandler = function () {
  67400. scene._removePendingData(loadingToken);
  67401. scene.getEngine().hideLoadingUI();
  67402. };
  67403. var errorHandler = function (message, exception) {
  67404. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67405. if (onError) {
  67406. onError(scene, errorMessage, exception);
  67407. }
  67408. else {
  67409. BABYLON.Tools.Error(errorMessage);
  67410. // should the exception be thrown?
  67411. }
  67412. disposeHandler();
  67413. };
  67414. var progressHandler = onProgress ? function (event) {
  67415. try {
  67416. onProgress(event);
  67417. }
  67418. catch (e) {
  67419. errorHandler("Error in onProgress callback", e);
  67420. }
  67421. } : undefined;
  67422. var successHandler = function () {
  67423. if (onSuccess) {
  67424. try {
  67425. onSuccess(scene);
  67426. }
  67427. catch (e) {
  67428. errorHandler("Error in onSuccess callback", e);
  67429. }
  67430. }
  67431. scene._removePendingData(loadingToken);
  67432. };
  67433. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67434. if (sceneFilename === "") {
  67435. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67436. }
  67437. if (plugin.load) {
  67438. var syncedPlugin = plugin;
  67439. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67440. return;
  67441. }
  67442. scene.loadingPluginName = plugin.name;
  67443. successHandler();
  67444. }
  67445. else {
  67446. var asyncedPlugin = plugin;
  67447. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67448. scene.loadingPluginName = plugin.name;
  67449. successHandler();
  67450. }).catch(function (error) {
  67451. errorHandler(error.message, error);
  67452. });
  67453. }
  67454. if (SceneLoader.ShowLoadingScreen) {
  67455. scene.executeWhenReady(function () {
  67456. scene.getEngine().hideLoadingUI();
  67457. });
  67458. }
  67459. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67460. };
  67461. /**
  67462. * Append a scene
  67463. * @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)
  67464. * @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)
  67465. * @param scene is the instance of BABYLON.Scene to append to
  67466. * @param onProgress a callback with a progress event for each file being loaded
  67467. * @param pluginExtension the extension used to determine the plugin
  67468. * @returns The given scene
  67469. */
  67470. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67471. if (sceneFilename === void 0) { sceneFilename = ""; }
  67472. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67473. if (onProgress === void 0) { onProgress = null; }
  67474. if (pluginExtension === void 0) { pluginExtension = null; }
  67475. return new Promise(function (resolve, reject) {
  67476. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67477. resolve(scene);
  67478. }, onProgress, function (scene, message, exception) {
  67479. reject(exception || new Error(message));
  67480. }, pluginExtension);
  67481. });
  67482. };
  67483. /**
  67484. * Load a scene into an asset container
  67485. * @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)
  67486. * @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)
  67487. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67488. * @param onSuccess a callback with the scene when import succeeds
  67489. * @param onProgress a callback with a progress event for each file being loaded
  67490. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67491. * @param pluginExtension the extension used to determine the plugin
  67492. * @returns The loaded plugin
  67493. */
  67494. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67495. if (sceneFilename === void 0) { sceneFilename = ""; }
  67496. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67497. if (onSuccess === void 0) { onSuccess = null; }
  67498. if (onProgress === void 0) { onProgress = null; }
  67499. if (onError === void 0) { onError = null; }
  67500. if (pluginExtension === void 0) { pluginExtension = null; }
  67501. if (!scene) {
  67502. BABYLON.Tools.Error("No scene available to load asset container to");
  67503. return null;
  67504. }
  67505. if (!sceneFilename) {
  67506. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67507. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67508. }
  67509. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67510. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67511. return null;
  67512. }
  67513. var loadingToken = {};
  67514. scene._addPendingData(loadingToken);
  67515. var disposeHandler = function () {
  67516. scene._removePendingData(loadingToken);
  67517. };
  67518. var errorHandler = function (message, exception) {
  67519. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67520. if (onError) {
  67521. onError(scene, errorMessage, exception);
  67522. }
  67523. else {
  67524. BABYLON.Tools.Error(errorMessage);
  67525. // should the exception be thrown?
  67526. }
  67527. disposeHandler();
  67528. };
  67529. var progressHandler = onProgress ? function (event) {
  67530. try {
  67531. onProgress(event);
  67532. }
  67533. catch (e) {
  67534. errorHandler("Error in onProgress callback", e);
  67535. }
  67536. } : undefined;
  67537. var successHandler = function (assets) {
  67538. if (onSuccess) {
  67539. try {
  67540. onSuccess(assets);
  67541. }
  67542. catch (e) {
  67543. errorHandler("Error in onSuccess callback", e);
  67544. }
  67545. }
  67546. scene._removePendingData(loadingToken);
  67547. };
  67548. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67549. if (plugin.loadAssetContainer) {
  67550. var syncedPlugin = plugin;
  67551. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67552. if (!assetContainer) {
  67553. return;
  67554. }
  67555. scene.loadingPluginName = plugin.name;
  67556. successHandler(assetContainer);
  67557. }
  67558. else if (plugin.loadAssetContainerAsync) {
  67559. var asyncedPlugin = plugin;
  67560. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67561. scene.loadingPluginName = plugin.name;
  67562. successHandler(assetContainer);
  67563. }).catch(function (error) {
  67564. errorHandler(error.message, error);
  67565. });
  67566. }
  67567. else {
  67568. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67569. }
  67570. if (SceneLoader.ShowLoadingScreen) {
  67571. scene.executeWhenReady(function () {
  67572. scene.getEngine().hideLoadingUI();
  67573. });
  67574. }
  67575. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67576. };
  67577. /**
  67578. * Load a scene into an asset container
  67579. * @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)
  67580. * @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)
  67581. * @param scene is the instance of BABYLON.Scene to append to
  67582. * @param onProgress a callback with a progress event for each file being loaded
  67583. * @param pluginExtension the extension used to determine the plugin
  67584. * @returns The loaded asset container
  67585. */
  67586. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67587. if (sceneFilename === void 0) { sceneFilename = ""; }
  67588. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67589. if (onProgress === void 0) { onProgress = null; }
  67590. if (pluginExtension === void 0) { pluginExtension = null; }
  67591. return new Promise(function (resolve, reject) {
  67592. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67593. resolve(assetContainer);
  67594. }, onProgress, function (scene, message, exception) {
  67595. reject(exception || new Error(message));
  67596. }, pluginExtension);
  67597. });
  67598. };
  67599. // Flags
  67600. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67601. SceneLoader._ShowLoadingScreen = true;
  67602. SceneLoader._CleanBoneMatrixWeights = false;
  67603. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67604. // Members
  67605. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67606. SceneLoader._registeredPlugins = {};
  67607. return SceneLoader;
  67608. }());
  67609. BABYLON.SceneLoader = SceneLoader;
  67610. ;
  67611. })(BABYLON || (BABYLON = {}));
  67612. //# sourceMappingURL=babylon.sceneLoader.js.map
  67613. var BABYLON;
  67614. (function (BABYLON) {
  67615. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67616. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67617. var parsedMaterial = parsedData.materials[index];
  67618. if (parsedMaterial.id === id) {
  67619. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67620. }
  67621. }
  67622. return null;
  67623. };
  67624. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67625. for (var i in names) {
  67626. if (mesh.name === names[i]) {
  67627. hierarchyIds.push(mesh.id);
  67628. return true;
  67629. }
  67630. }
  67631. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67632. hierarchyIds.push(mesh.id);
  67633. return true;
  67634. }
  67635. return false;
  67636. };
  67637. var logOperation = function (operation, producer) {
  67638. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67639. };
  67640. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67641. if (addToScene === void 0) { addToScene = false; }
  67642. var container = new BABYLON.AssetContainer(scene);
  67643. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67644. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67645. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67646. // and avoid problems with multiple concurrent .babylon loads.
  67647. var log = "importScene has failed JSON parse";
  67648. try {
  67649. var parsedData = JSON.parse(data);
  67650. log = "";
  67651. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67652. var index;
  67653. var cache;
  67654. // Lights
  67655. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67656. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67657. var parsedLight = parsedData.lights[index];
  67658. var light = BABYLON.Light.Parse(parsedLight, scene);
  67659. if (light) {
  67660. container.lights.push(light);
  67661. log += (index === 0 ? "\n\tLights:" : "");
  67662. log += "\n\t\t" + light.toString(fullDetails);
  67663. }
  67664. }
  67665. }
  67666. // Animations
  67667. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67668. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67669. var parsedAnimation = parsedData.animations[index];
  67670. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67671. scene.animations.push(animation);
  67672. container.animations.push(animation);
  67673. log += (index === 0 ? "\n\tAnimations:" : "");
  67674. log += "\n\t\t" + animation.toString(fullDetails);
  67675. }
  67676. }
  67677. // Materials
  67678. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67679. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67680. var parsedMaterial = parsedData.materials[index];
  67681. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67682. container.materials.push(mat);
  67683. log += (index === 0 ? "\n\tMaterials:" : "");
  67684. log += "\n\t\t" + mat.toString(fullDetails);
  67685. }
  67686. }
  67687. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67688. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67689. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67690. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67691. container.multiMaterials.push(mmat);
  67692. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67693. log += "\n\t\t" + mmat.toString(fullDetails);
  67694. }
  67695. }
  67696. // Morph targets
  67697. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67698. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67699. var managerData = _a[_i];
  67700. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67701. }
  67702. }
  67703. // Skeletons
  67704. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67705. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67706. var parsedSkeleton = parsedData.skeletons[index];
  67707. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67708. container.skeletons.push(skeleton);
  67709. log += (index === 0 ? "\n\tSkeletons:" : "");
  67710. log += "\n\t\t" + skeleton.toString(fullDetails);
  67711. }
  67712. }
  67713. // Geometries
  67714. var geometries = parsedData.geometries;
  67715. if (geometries !== undefined && geometries !== null) {
  67716. var addedGeometry = new Array();
  67717. // Boxes
  67718. var boxes = geometries.boxes;
  67719. if (boxes !== undefined && boxes !== null) {
  67720. for (index = 0, cache = boxes.length; index < cache; index++) {
  67721. var parsedBox = boxes[index];
  67722. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67723. }
  67724. }
  67725. // Spheres
  67726. var spheres = geometries.spheres;
  67727. if (spheres !== undefined && spheres !== null) {
  67728. for (index = 0, cache = spheres.length; index < cache; index++) {
  67729. var parsedSphere = spheres[index];
  67730. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67731. }
  67732. }
  67733. // Cylinders
  67734. var cylinders = geometries.cylinders;
  67735. if (cylinders !== undefined && cylinders !== null) {
  67736. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67737. var parsedCylinder = cylinders[index];
  67738. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67739. }
  67740. }
  67741. // Toruses
  67742. var toruses = geometries.toruses;
  67743. if (toruses !== undefined && toruses !== null) {
  67744. for (index = 0, cache = toruses.length; index < cache; index++) {
  67745. var parsedTorus = toruses[index];
  67746. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67747. }
  67748. }
  67749. // Grounds
  67750. var grounds = geometries.grounds;
  67751. if (grounds !== undefined && grounds !== null) {
  67752. for (index = 0, cache = grounds.length; index < cache; index++) {
  67753. var parsedGround = grounds[index];
  67754. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67755. }
  67756. }
  67757. // Planes
  67758. var planes = geometries.planes;
  67759. if (planes !== undefined && planes !== null) {
  67760. for (index = 0, cache = planes.length; index < cache; index++) {
  67761. var parsedPlane = planes[index];
  67762. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67763. }
  67764. }
  67765. // TorusKnots
  67766. var torusKnots = geometries.torusKnots;
  67767. if (torusKnots !== undefined && torusKnots !== null) {
  67768. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67769. var parsedTorusKnot = torusKnots[index];
  67770. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67771. }
  67772. }
  67773. // VertexData
  67774. var vertexData = geometries.vertexData;
  67775. if (vertexData !== undefined && vertexData !== null) {
  67776. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67777. var parsedVertexData = vertexData[index];
  67778. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67779. }
  67780. }
  67781. addedGeometry.forEach(function (g) {
  67782. if (g) {
  67783. container.geometries.push(g);
  67784. }
  67785. });
  67786. }
  67787. // Transform nodes
  67788. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67789. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67790. var parsedTransformNode = parsedData.transformNodes[index];
  67791. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67792. container.transformNodes.push(node);
  67793. }
  67794. }
  67795. // Meshes
  67796. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67797. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67798. var parsedMesh = parsedData.meshes[index];
  67799. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67800. container.meshes.push(mesh);
  67801. log += (index === 0 ? "\n\tMeshes:" : "");
  67802. log += "\n\t\t" + mesh.toString(fullDetails);
  67803. }
  67804. }
  67805. // Cameras
  67806. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67807. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67808. var parsedCamera = parsedData.cameras[index];
  67809. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67810. container.cameras.push(camera);
  67811. log += (index === 0 ? "\n\tCameras:" : "");
  67812. log += "\n\t\t" + camera.toString(fullDetails);
  67813. }
  67814. }
  67815. // Browsing all the graph to connect the dots
  67816. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67817. var camera = scene.cameras[index];
  67818. if (camera._waitingParentId) {
  67819. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67820. camera._waitingParentId = null;
  67821. }
  67822. }
  67823. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67824. var light_1 = scene.lights[index];
  67825. if (light_1 && light_1._waitingParentId) {
  67826. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67827. light_1._waitingParentId = null;
  67828. }
  67829. }
  67830. // Sounds
  67831. // TODO: add sound
  67832. var loadedSounds = [];
  67833. var loadedSound;
  67834. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67835. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67836. var parsedSound = parsedData.sounds[index];
  67837. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67838. if (!parsedSound.url)
  67839. parsedSound.url = parsedSound.name;
  67840. if (!loadedSounds[parsedSound.url]) {
  67841. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67842. loadedSounds[parsedSound.url] = loadedSound;
  67843. container.sounds.push(loadedSound);
  67844. }
  67845. else {
  67846. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67847. }
  67848. }
  67849. else {
  67850. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67851. }
  67852. }
  67853. }
  67854. loadedSounds = [];
  67855. // Connect parents & children and parse actions
  67856. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67857. var transformNode = scene.transformNodes[index];
  67858. if (transformNode._waitingParentId) {
  67859. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67860. transformNode._waitingParentId = null;
  67861. }
  67862. }
  67863. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67864. var mesh = scene.meshes[index];
  67865. if (mesh._waitingParentId) {
  67866. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67867. mesh._waitingParentId = null;
  67868. }
  67869. if (mesh._waitingActions) {
  67870. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67871. mesh._waitingActions = null;
  67872. }
  67873. }
  67874. // freeze world matrix application
  67875. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67876. var currentMesh = scene.meshes[index];
  67877. if (currentMesh._waitingFreezeWorldMatrix) {
  67878. currentMesh.freezeWorldMatrix();
  67879. currentMesh._waitingFreezeWorldMatrix = null;
  67880. }
  67881. else {
  67882. currentMesh.computeWorldMatrix(true);
  67883. }
  67884. }
  67885. // Particles Systems
  67886. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67887. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67888. var parsedParticleSystem = parsedData.particleSystems[index];
  67889. if (parsedParticleSystem.activeParticleCount) {
  67890. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67891. container.particleSystems.push(ps);
  67892. }
  67893. else {
  67894. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67895. container.particleSystems.push(ps);
  67896. }
  67897. }
  67898. }
  67899. // Lens flares
  67900. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67901. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67902. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67903. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67904. container.lensFlareSystems.push(lf);
  67905. }
  67906. }
  67907. // Shadows
  67908. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67909. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67910. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67911. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67912. container.shadowGenerators.push(sg);
  67913. }
  67914. }
  67915. // Lights exclusions / inclusions
  67916. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67917. var light_2 = scene.lights[index];
  67918. // Excluded check
  67919. if (light_2._excludedMeshesIds.length > 0) {
  67920. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67921. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67922. if (excludedMesh) {
  67923. light_2.excludedMeshes.push(excludedMesh);
  67924. }
  67925. }
  67926. light_2._excludedMeshesIds = [];
  67927. }
  67928. // Included check
  67929. if (light_2._includedOnlyMeshesIds.length > 0) {
  67930. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67931. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67932. if (includedOnlyMesh) {
  67933. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67934. }
  67935. }
  67936. light_2._includedOnlyMeshesIds = [];
  67937. }
  67938. }
  67939. // Effect layers
  67940. if (parsedData.effectLayers) {
  67941. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67942. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67943. container.effectLayers.push(effectLayer);
  67944. }
  67945. }
  67946. // Actions (scene)
  67947. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67948. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67949. }
  67950. if (!addToScene) {
  67951. container.removeAllFromScene();
  67952. }
  67953. }
  67954. catch (err) {
  67955. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67956. if (onError) {
  67957. onError(msg, err);
  67958. }
  67959. else {
  67960. BABYLON.Tools.Log(msg);
  67961. throw err;
  67962. }
  67963. }
  67964. finally {
  67965. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67966. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67967. }
  67968. }
  67969. return container;
  67970. };
  67971. BABYLON.SceneLoader.RegisterPlugin({
  67972. name: "babylon.js",
  67973. extensions: ".babylon",
  67974. canDirectLoad: function (data) {
  67975. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67976. return true;
  67977. }
  67978. return false;
  67979. },
  67980. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67981. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67982. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67983. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67984. // and avoid problems with multiple concurrent .babylon loads.
  67985. var log = "importMesh has failed JSON parse";
  67986. try {
  67987. var parsedData = JSON.parse(data);
  67988. log = "";
  67989. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67990. if (!meshesNames) {
  67991. meshesNames = null;
  67992. }
  67993. else if (!Array.isArray(meshesNames)) {
  67994. meshesNames = [meshesNames];
  67995. }
  67996. var hierarchyIds = new Array();
  67997. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67998. var loadedSkeletonsIds = [];
  67999. var loadedMaterialsIds = [];
  68000. var index;
  68001. var cache;
  68002. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68003. var parsedMesh = parsedData.meshes[index];
  68004. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68005. if (meshesNames !== null) {
  68006. // Remove found mesh name from list.
  68007. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68008. }
  68009. //Geometry?
  68010. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68011. //does the file contain geometries?
  68012. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68013. //find the correct geometry and add it to the scene
  68014. var found = false;
  68015. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68016. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68017. return;
  68018. }
  68019. else {
  68020. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68021. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68022. switch (geometryType) {
  68023. case "boxes":
  68024. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68025. break;
  68026. case "spheres":
  68027. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68028. break;
  68029. case "cylinders":
  68030. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68031. break;
  68032. case "toruses":
  68033. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68034. break;
  68035. case "grounds":
  68036. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68037. break;
  68038. case "planes":
  68039. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68040. break;
  68041. case "torusKnots":
  68042. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68043. break;
  68044. case "vertexData":
  68045. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68046. break;
  68047. }
  68048. found = true;
  68049. }
  68050. });
  68051. }
  68052. });
  68053. if (found === false) {
  68054. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68055. }
  68056. }
  68057. }
  68058. // Material ?
  68059. if (parsedMesh.materialId) {
  68060. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68061. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68062. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68063. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68064. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68065. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68066. var subMatId = parsedMultiMaterial.materials[matIndex];
  68067. loadedMaterialsIds.push(subMatId);
  68068. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68069. if (mat) {
  68070. log += "\n\tMaterial " + mat.toString(fullDetails);
  68071. }
  68072. }
  68073. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68074. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68075. if (mmat) {
  68076. materialFound = true;
  68077. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68078. }
  68079. break;
  68080. }
  68081. }
  68082. }
  68083. if (materialFound === false) {
  68084. loadedMaterialsIds.push(parsedMesh.materialId);
  68085. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68086. if (!mat) {
  68087. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68088. }
  68089. else {
  68090. log += "\n\tMaterial " + mat.toString(fullDetails);
  68091. }
  68092. }
  68093. }
  68094. // Skeleton ?
  68095. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68096. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68097. if (skeletonAlreadyLoaded === false) {
  68098. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68099. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68100. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68101. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68102. skeletons.push(skeleton);
  68103. loadedSkeletonsIds.push(parsedSkeleton.id);
  68104. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68105. }
  68106. }
  68107. }
  68108. }
  68109. // Morph targets ?
  68110. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68111. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68112. var managerData = _a[_i];
  68113. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68114. }
  68115. }
  68116. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68117. meshes.push(mesh);
  68118. log += "\n\tMesh " + mesh.toString(fullDetails);
  68119. }
  68120. }
  68121. // Connecting parents
  68122. var currentMesh;
  68123. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68124. currentMesh = scene.meshes[index];
  68125. if (currentMesh._waitingParentId) {
  68126. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68127. currentMesh._waitingParentId = null;
  68128. }
  68129. }
  68130. // freeze and compute world matrix application
  68131. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68132. currentMesh = scene.meshes[index];
  68133. if (currentMesh._waitingFreezeWorldMatrix) {
  68134. currentMesh.freezeWorldMatrix();
  68135. currentMesh._waitingFreezeWorldMatrix = null;
  68136. }
  68137. else {
  68138. currentMesh.computeWorldMatrix(true);
  68139. }
  68140. }
  68141. }
  68142. // Particles
  68143. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68144. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68145. var parsedParticleSystem = parsedData.particleSystems[index];
  68146. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68147. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68148. }
  68149. }
  68150. }
  68151. return true;
  68152. }
  68153. catch (err) {
  68154. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68155. if (onError) {
  68156. onError(msg, err);
  68157. }
  68158. else {
  68159. BABYLON.Tools.Log(msg);
  68160. throw err;
  68161. }
  68162. }
  68163. finally {
  68164. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68165. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68166. }
  68167. }
  68168. return false;
  68169. },
  68170. load: function (scene, data, rootUrl, onError) {
  68171. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68172. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68173. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68174. // and avoid problems with multiple concurrent .babylon loads.
  68175. var log = "importScene has failed JSON parse";
  68176. try {
  68177. var parsedData = JSON.parse(data);
  68178. log = "";
  68179. // Scene
  68180. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68181. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68182. }
  68183. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68184. scene.autoClear = parsedData.autoClear;
  68185. }
  68186. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68187. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68188. }
  68189. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68190. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68191. }
  68192. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68193. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68194. }
  68195. // Fog
  68196. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68197. scene.fogMode = parsedData.fogMode;
  68198. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68199. scene.fogStart = parsedData.fogStart;
  68200. scene.fogEnd = parsedData.fogEnd;
  68201. scene.fogDensity = parsedData.fogDensity;
  68202. log += "\tFog mode for scene: ";
  68203. switch (scene.fogMode) {
  68204. // getters not compiling, so using hardcoded
  68205. case 1:
  68206. log += "exp\n";
  68207. break;
  68208. case 2:
  68209. log += "exp2\n";
  68210. break;
  68211. case 3:
  68212. log += "linear\n";
  68213. break;
  68214. }
  68215. }
  68216. //Physics
  68217. if (parsedData.physicsEnabled) {
  68218. var physicsPlugin;
  68219. if (parsedData.physicsEngine === "cannon") {
  68220. physicsPlugin = new BABYLON.CannonJSPlugin();
  68221. }
  68222. else if (parsedData.physicsEngine === "oimo") {
  68223. physicsPlugin = new BABYLON.OimoJSPlugin();
  68224. }
  68225. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68226. //else - default engine, which is currently oimo
  68227. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68228. scene.enablePhysics(physicsGravity, physicsPlugin);
  68229. }
  68230. // Metadata
  68231. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68232. scene.metadata = parsedData.metadata;
  68233. }
  68234. //collisions, if defined. otherwise, default is true
  68235. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68236. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68237. }
  68238. scene.workerCollisions = !!parsedData.workerCollisions;
  68239. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68240. if (!container) {
  68241. return false;
  68242. }
  68243. if (parsedData.autoAnimate) {
  68244. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68245. }
  68246. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68247. scene.setActiveCameraByID(parsedData.activeCameraID);
  68248. }
  68249. // Environment texture
  68250. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68251. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68252. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68253. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68254. if (parsedData.environmentTextureRotationY) {
  68255. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68256. }
  68257. scene.environmentTexture = hdrTexture;
  68258. }
  68259. else {
  68260. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68261. if (parsedData.environmentTextureRotationY) {
  68262. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68263. }
  68264. scene.environmentTexture = cubeTexture;
  68265. }
  68266. if (parsedData.createDefaultSkybox === true) {
  68267. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68268. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68269. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68270. }
  68271. }
  68272. // Finish
  68273. return true;
  68274. }
  68275. catch (err) {
  68276. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68277. if (onError) {
  68278. onError(msg, err);
  68279. }
  68280. else {
  68281. BABYLON.Tools.Log(msg);
  68282. throw err;
  68283. }
  68284. }
  68285. finally {
  68286. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68287. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68288. }
  68289. }
  68290. return false;
  68291. },
  68292. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68293. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68294. return container;
  68295. }
  68296. });
  68297. })(BABYLON || (BABYLON = {}));
  68298. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68299. var BABYLON;
  68300. (function (BABYLON) {
  68301. var FilesInput = /** @class */ (function () {
  68302. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68303. this.onProcessFileCallback = function () { return true; };
  68304. this._engine = engine;
  68305. this._currentScene = scene;
  68306. this._sceneLoadedCallback = sceneLoadedCallback;
  68307. this._progressCallback = progressCallback;
  68308. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68309. this._textureLoadingCallback = textureLoadingCallback;
  68310. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68311. this._onReloadCallback = onReloadCallback;
  68312. this._errorCallback = errorCallback;
  68313. }
  68314. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68315. var _this = this;
  68316. if (elementToMonitor) {
  68317. this._elementToMonitor = elementToMonitor;
  68318. this._dragEnterHandler = function (e) { _this.drag(e); };
  68319. this._dragOverHandler = function (e) { _this.drag(e); };
  68320. this._dropHandler = function (e) { _this.drop(e); };
  68321. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68322. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68323. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68324. }
  68325. };
  68326. FilesInput.prototype.dispose = function () {
  68327. if (!this._elementToMonitor) {
  68328. return;
  68329. }
  68330. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68331. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68332. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68333. };
  68334. FilesInput.prototype.renderFunction = function () {
  68335. if (this._additionalRenderLoopLogicCallback) {
  68336. this._additionalRenderLoopLogicCallback();
  68337. }
  68338. if (this._currentScene) {
  68339. if (this._textureLoadingCallback) {
  68340. var remaining = this._currentScene.getWaitingItemsCount();
  68341. if (remaining > 0) {
  68342. this._textureLoadingCallback(remaining);
  68343. }
  68344. }
  68345. this._currentScene.render();
  68346. }
  68347. };
  68348. FilesInput.prototype.drag = function (e) {
  68349. e.stopPropagation();
  68350. e.preventDefault();
  68351. };
  68352. FilesInput.prototype.drop = function (eventDrop) {
  68353. eventDrop.stopPropagation();
  68354. eventDrop.preventDefault();
  68355. this.loadFiles(eventDrop);
  68356. };
  68357. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68358. var _this = this;
  68359. var reader = folder.createReader();
  68360. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68361. reader.readEntries(function (entries) {
  68362. remaining.count += entries.length;
  68363. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68364. var entry = entries_1[_i];
  68365. if (entry.isFile) {
  68366. entry.file(function (file) {
  68367. file.correctName = relativePath + file.name;
  68368. files.push(file);
  68369. if (--remaining.count === 0) {
  68370. callback();
  68371. }
  68372. });
  68373. }
  68374. else if (entry.isDirectory) {
  68375. _this._traverseFolder(entry, files, remaining, callback);
  68376. }
  68377. }
  68378. if (--remaining.count) {
  68379. callback();
  68380. }
  68381. });
  68382. };
  68383. FilesInput.prototype._processFiles = function (files) {
  68384. for (var i = 0; i < files.length; i++) {
  68385. var name = files[i].correctName.toLowerCase();
  68386. var extension = name.split('.').pop();
  68387. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68388. continue;
  68389. }
  68390. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68391. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68392. this._sceneFileToLoad = files[i];
  68393. }
  68394. else {
  68395. FilesInput.FilesToLoad[name] = files[i];
  68396. }
  68397. }
  68398. };
  68399. FilesInput.prototype.loadFiles = function (event) {
  68400. var _this = this;
  68401. if (this._startingProcessingFilesCallback)
  68402. this._startingProcessingFilesCallback();
  68403. // Handling data transfer via drag'n'drop
  68404. if (event && event.dataTransfer && event.dataTransfer.files) {
  68405. this._filesToLoad = event.dataTransfer.files;
  68406. }
  68407. // Handling files from input files
  68408. if (event && event.target && event.target.files) {
  68409. this._filesToLoad = event.target.files;
  68410. }
  68411. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68412. var files_1 = new Array();
  68413. var folders = [];
  68414. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68415. for (var i = 0; i < this._filesToLoad.length; i++) {
  68416. var fileToLoad = this._filesToLoad[i];
  68417. var name_1 = fileToLoad.name.toLowerCase();
  68418. var entry = void 0;
  68419. fileToLoad.correctName = name_1;
  68420. if (items) {
  68421. var item = items[i];
  68422. if (item.getAsEntry) {
  68423. entry = item.getAsEntry();
  68424. }
  68425. else if (item.webkitGetAsEntry) {
  68426. entry = item.webkitGetAsEntry();
  68427. }
  68428. }
  68429. if (!entry) {
  68430. files_1.push(fileToLoad);
  68431. }
  68432. else {
  68433. if (entry.isDirectory) {
  68434. folders.push(entry);
  68435. }
  68436. else {
  68437. files_1.push(fileToLoad);
  68438. }
  68439. }
  68440. }
  68441. if (folders.length === 0) {
  68442. this._processFiles(files_1);
  68443. this._processReload();
  68444. }
  68445. else {
  68446. var remaining = { count: folders.length };
  68447. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68448. var folder = folders_1[_i];
  68449. this._traverseFolder(folder, files_1, remaining, function () {
  68450. _this._processFiles(files_1);
  68451. if (remaining.count === 0) {
  68452. _this._processReload();
  68453. }
  68454. });
  68455. }
  68456. }
  68457. }
  68458. };
  68459. FilesInput.prototype._processReload = function () {
  68460. if (this._onReloadCallback) {
  68461. this._onReloadCallback(this._sceneFileToLoad);
  68462. }
  68463. else {
  68464. this.reload();
  68465. }
  68466. };
  68467. FilesInput.prototype.reload = function () {
  68468. var _this = this;
  68469. // If a scene file has been provided
  68470. if (this._sceneFileToLoad) {
  68471. if (this._currentScene) {
  68472. if (BABYLON.Tools.errorsCount > 0) {
  68473. BABYLON.Tools.ClearLogCache();
  68474. }
  68475. this._engine.stopRenderLoop();
  68476. }
  68477. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68478. if (_this._progressCallback) {
  68479. _this._progressCallback(progress);
  68480. }
  68481. }).then(function (scene) {
  68482. if (_this._currentScene) {
  68483. _this._currentScene.dispose();
  68484. }
  68485. _this._currentScene = scene;
  68486. if (_this._sceneLoadedCallback) {
  68487. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68488. }
  68489. // Wait for textures and shaders to be ready
  68490. _this._currentScene.executeWhenReady(function () {
  68491. _this._engine.runRenderLoop(function () {
  68492. _this.renderFunction();
  68493. });
  68494. });
  68495. }).catch(function (error) {
  68496. if (_this._errorCallback) {
  68497. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68498. }
  68499. });
  68500. }
  68501. else {
  68502. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68503. }
  68504. };
  68505. FilesInput.FilesToLoad = {};
  68506. return FilesInput;
  68507. }());
  68508. BABYLON.FilesInput = FilesInput;
  68509. })(BABYLON || (BABYLON = {}));
  68510. //# sourceMappingURL=babylon.filesInput.js.map
  68511. var BABYLON;
  68512. (function (BABYLON) {
  68513. /**
  68514. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68515. * The underlying implementation relies on an associative array to ensure the best performances.
  68516. * The value can be anything including 'null' but except 'undefined'
  68517. */
  68518. var StringDictionary = /** @class */ (function () {
  68519. function StringDictionary() {
  68520. this._count = 0;
  68521. this._data = {};
  68522. }
  68523. /**
  68524. * This will clear this dictionary and copy the content from the 'source' one.
  68525. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68526. * @param source the dictionary to take the content from and copy to this dictionary
  68527. */
  68528. StringDictionary.prototype.copyFrom = function (source) {
  68529. var _this = this;
  68530. this.clear();
  68531. source.forEach(function (t, v) { return _this.add(t, v); });
  68532. };
  68533. /**
  68534. * Get a value based from its key
  68535. * @param key the given key to get the matching value from
  68536. * @return the value if found, otherwise undefined is returned
  68537. */
  68538. StringDictionary.prototype.get = function (key) {
  68539. var val = this._data[key];
  68540. if (val !== undefined) {
  68541. return val;
  68542. }
  68543. return undefined;
  68544. };
  68545. /**
  68546. * Get a value from its key or add it if it doesn't exist.
  68547. * This method will ensure you that a given key/data will be present in the dictionary.
  68548. * @param key the given key to get the matching value from
  68549. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68550. * The factory will only be invoked if there's no data for the given key.
  68551. * @return the value corresponding to the key.
  68552. */
  68553. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68554. var val = this.get(key);
  68555. if (val !== undefined) {
  68556. return val;
  68557. }
  68558. val = factory(key);
  68559. if (val) {
  68560. this.add(key, val);
  68561. }
  68562. return val;
  68563. };
  68564. /**
  68565. * Get a value from its key if present in the dictionary otherwise add it
  68566. * @param key the key to get the value from
  68567. * @param val if there's no such key/value pair in the dictionary add it with this value
  68568. * @return the value corresponding to the key
  68569. */
  68570. StringDictionary.prototype.getOrAdd = function (key, val) {
  68571. var curVal = this.get(key);
  68572. if (curVal !== undefined) {
  68573. return curVal;
  68574. }
  68575. this.add(key, val);
  68576. return val;
  68577. };
  68578. /**
  68579. * Check if there's a given key in the dictionary
  68580. * @param key the key to check for
  68581. * @return true if the key is present, false otherwise
  68582. */
  68583. StringDictionary.prototype.contains = function (key) {
  68584. return this._data[key] !== undefined;
  68585. };
  68586. /**
  68587. * Add a new key and its corresponding value
  68588. * @param key the key to add
  68589. * @param value the value corresponding to the key
  68590. * @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
  68591. */
  68592. StringDictionary.prototype.add = function (key, value) {
  68593. if (this._data[key] !== undefined) {
  68594. return false;
  68595. }
  68596. this._data[key] = value;
  68597. ++this._count;
  68598. return true;
  68599. };
  68600. StringDictionary.prototype.set = function (key, value) {
  68601. if (this._data[key] === undefined) {
  68602. return false;
  68603. }
  68604. this._data[key] = value;
  68605. return true;
  68606. };
  68607. /**
  68608. * Get the element of the given key and remove it from the dictionary
  68609. * @param key
  68610. */
  68611. StringDictionary.prototype.getAndRemove = function (key) {
  68612. var val = this.get(key);
  68613. if (val !== undefined) {
  68614. delete this._data[key];
  68615. --this._count;
  68616. return val;
  68617. }
  68618. return null;
  68619. };
  68620. /**
  68621. * Remove a key/value from the dictionary.
  68622. * @param key the key to remove
  68623. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68624. */
  68625. StringDictionary.prototype.remove = function (key) {
  68626. if (this.contains(key)) {
  68627. delete this._data[key];
  68628. --this._count;
  68629. return true;
  68630. }
  68631. return false;
  68632. };
  68633. /**
  68634. * Clear the whole content of the dictionary
  68635. */
  68636. StringDictionary.prototype.clear = function () {
  68637. this._data = {};
  68638. this._count = 0;
  68639. };
  68640. Object.defineProperty(StringDictionary.prototype, "count", {
  68641. get: function () {
  68642. return this._count;
  68643. },
  68644. enumerable: true,
  68645. configurable: true
  68646. });
  68647. /**
  68648. * Execute a callback on each key/val of the dictionary.
  68649. * Note that you can remove any element in this dictionary in the callback implementation
  68650. * @param callback the callback to execute on a given key/value pair
  68651. */
  68652. StringDictionary.prototype.forEach = function (callback) {
  68653. for (var cur in this._data) {
  68654. var val = this._data[cur];
  68655. callback(cur, val);
  68656. }
  68657. };
  68658. /**
  68659. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68660. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68661. * Note that you can remove any element in this dictionary in the callback implementation
  68662. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68663. */
  68664. StringDictionary.prototype.first = function (callback) {
  68665. for (var cur in this._data) {
  68666. var val = this._data[cur];
  68667. var res = callback(cur, val);
  68668. if (res) {
  68669. return res;
  68670. }
  68671. }
  68672. return null;
  68673. };
  68674. return StringDictionary;
  68675. }());
  68676. BABYLON.StringDictionary = StringDictionary;
  68677. })(BABYLON || (BABYLON = {}));
  68678. //# sourceMappingURL=babylon.stringDictionary.js.map
  68679. var BABYLON;
  68680. (function (BABYLON) {
  68681. var Tags = /** @class */ (function () {
  68682. function Tags() {
  68683. }
  68684. Tags.EnableFor = function (obj) {
  68685. obj._tags = obj._tags || {};
  68686. obj.hasTags = function () {
  68687. return Tags.HasTags(obj);
  68688. };
  68689. obj.addTags = function (tagsString) {
  68690. return Tags.AddTagsTo(obj, tagsString);
  68691. };
  68692. obj.removeTags = function (tagsString) {
  68693. return Tags.RemoveTagsFrom(obj, tagsString);
  68694. };
  68695. obj.matchesTagsQuery = function (tagsQuery) {
  68696. return Tags.MatchesQuery(obj, tagsQuery);
  68697. };
  68698. };
  68699. Tags.DisableFor = function (obj) {
  68700. delete obj._tags;
  68701. delete obj.hasTags;
  68702. delete obj.addTags;
  68703. delete obj.removeTags;
  68704. delete obj.matchesTagsQuery;
  68705. };
  68706. Tags.HasTags = function (obj) {
  68707. if (!obj._tags) {
  68708. return false;
  68709. }
  68710. return !BABYLON.Tools.IsEmpty(obj._tags);
  68711. };
  68712. Tags.GetTags = function (obj, asString) {
  68713. if (asString === void 0) { asString = true; }
  68714. if (!obj._tags) {
  68715. return null;
  68716. }
  68717. if (asString) {
  68718. var tagsArray = [];
  68719. for (var tag in obj._tags) {
  68720. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68721. tagsArray.push(tag);
  68722. }
  68723. }
  68724. return tagsArray.join(" ");
  68725. }
  68726. else {
  68727. return obj._tags;
  68728. }
  68729. };
  68730. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68731. // a tag cannot start with '||', '&&', and '!'
  68732. // it cannot contain whitespaces
  68733. Tags.AddTagsTo = function (obj, tagsString) {
  68734. if (!tagsString) {
  68735. return;
  68736. }
  68737. if (typeof tagsString !== "string") {
  68738. return;
  68739. }
  68740. var tags = tagsString.split(" ");
  68741. tags.forEach(function (tag, index, array) {
  68742. Tags._AddTagTo(obj, tag);
  68743. });
  68744. };
  68745. Tags._AddTagTo = function (obj, tag) {
  68746. tag = tag.trim();
  68747. if (tag === "" || tag === "true" || tag === "false") {
  68748. return;
  68749. }
  68750. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68751. return;
  68752. }
  68753. Tags.EnableFor(obj);
  68754. obj._tags[tag] = true;
  68755. };
  68756. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68757. if (!Tags.HasTags(obj)) {
  68758. return;
  68759. }
  68760. var tags = tagsString.split(" ");
  68761. for (var t in tags) {
  68762. Tags._RemoveTagFrom(obj, tags[t]);
  68763. }
  68764. };
  68765. Tags._RemoveTagFrom = function (obj, tag) {
  68766. delete obj._tags[tag];
  68767. };
  68768. Tags.MatchesQuery = function (obj, tagsQuery) {
  68769. if (tagsQuery === undefined) {
  68770. return true;
  68771. }
  68772. if (tagsQuery === "") {
  68773. return Tags.HasTags(obj);
  68774. }
  68775. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68776. };
  68777. return Tags;
  68778. }());
  68779. BABYLON.Tags = Tags;
  68780. })(BABYLON || (BABYLON = {}));
  68781. //# sourceMappingURL=babylon.tags.js.map
  68782. var BABYLON;
  68783. (function (BABYLON) {
  68784. /**
  68785. * Class used to evalaute queries containing `and` and `or` operators
  68786. */
  68787. var AndOrNotEvaluator = /** @class */ (function () {
  68788. function AndOrNotEvaluator() {
  68789. }
  68790. /**
  68791. * Evaluate a query
  68792. * @param query defines the query to evaluate
  68793. * @param evaluateCallback defines the callback used to filter result
  68794. * @returns true if the query matches
  68795. */
  68796. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68797. if (!query.match(/\([^\(\)]*\)/g)) {
  68798. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68799. }
  68800. else {
  68801. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68802. // remove parenthesis
  68803. r = r.slice(1, r.length - 1);
  68804. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68805. });
  68806. }
  68807. if (query === "true") {
  68808. return true;
  68809. }
  68810. if (query === "false") {
  68811. return false;
  68812. }
  68813. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68814. };
  68815. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68816. evaluateCallback = evaluateCallback || (function (r) {
  68817. return r === "true" ? true : false;
  68818. });
  68819. var result;
  68820. var or = parenthesisContent.split("||");
  68821. for (var i in or) {
  68822. if (or.hasOwnProperty(i)) {
  68823. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68824. var and = ori.split("&&");
  68825. if (and.length > 1) {
  68826. for (var j = 0; j < and.length; ++j) {
  68827. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68828. if (andj !== "true" && andj !== "false") {
  68829. if (andj[0] === "!") {
  68830. result = !evaluateCallback(andj.substring(1));
  68831. }
  68832. else {
  68833. result = evaluateCallback(andj);
  68834. }
  68835. }
  68836. else {
  68837. result = andj === "true" ? true : false;
  68838. }
  68839. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68840. ori = "false";
  68841. break;
  68842. }
  68843. }
  68844. }
  68845. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68846. result = true;
  68847. break;
  68848. }
  68849. // result equals false (or undefined)
  68850. if (ori !== "true" && ori !== "false") {
  68851. if (ori[0] === "!") {
  68852. result = !evaluateCallback(ori.substring(1));
  68853. }
  68854. else {
  68855. result = evaluateCallback(ori);
  68856. }
  68857. }
  68858. else {
  68859. result = ori === "true" ? true : false;
  68860. }
  68861. }
  68862. }
  68863. // the whole parenthesis scope is replaced by 'true' or 'false'
  68864. return result ? "true" : "false";
  68865. };
  68866. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68867. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68868. // remove whitespaces
  68869. r = r.replace(/[\s]/g, function () { return ""; });
  68870. return r.length % 2 ? "!" : "";
  68871. });
  68872. booleanString = booleanString.trim();
  68873. if (booleanString === "!true") {
  68874. booleanString = "false";
  68875. }
  68876. else if (booleanString === "!false") {
  68877. booleanString = "true";
  68878. }
  68879. return booleanString;
  68880. };
  68881. return AndOrNotEvaluator;
  68882. }());
  68883. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68884. })(BABYLON || (BABYLON = {}));
  68885. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68886. var BABYLON;
  68887. (function (BABYLON) {
  68888. /**
  68889. * Class used to enable access to IndexedDB
  68890. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68891. */
  68892. var Database = /** @class */ (function () {
  68893. /**
  68894. * Creates a new Database
  68895. * @param urlToScene defines the url to load the scene
  68896. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68897. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68898. */
  68899. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68900. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68901. var _this = this;
  68902. // Handling various flavors of prefixed version of IndexedDB
  68903. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68904. this.callbackManifestChecked = callbackManifestChecked;
  68905. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68906. this.db = null;
  68907. this._enableSceneOffline = false;
  68908. this._enableTexturesOffline = false;
  68909. this.manifestVersionFound = 0;
  68910. this.mustUpdateRessources = false;
  68911. this.hasReachedQuota = false;
  68912. if (!Database.IDBStorageEnabled) {
  68913. this.callbackManifestChecked(true);
  68914. }
  68915. else {
  68916. if (disableManifestCheck) {
  68917. this._enableSceneOffline = true;
  68918. this._enableTexturesOffline = true;
  68919. this.manifestVersionFound = 1;
  68920. BABYLON.Tools.SetImmediate(function () {
  68921. _this.callbackManifestChecked(true);
  68922. });
  68923. }
  68924. else {
  68925. this._checkManifestFile();
  68926. }
  68927. }
  68928. }
  68929. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68930. /**
  68931. * Gets a boolean indicating if scene must be saved in the database
  68932. */
  68933. get: function () {
  68934. return this._enableSceneOffline;
  68935. },
  68936. enumerable: true,
  68937. configurable: true
  68938. });
  68939. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68940. /**
  68941. * Gets a boolean indicating if textures must be saved in the database
  68942. */
  68943. get: function () {
  68944. return this._enableTexturesOffline;
  68945. },
  68946. enumerable: true,
  68947. configurable: true
  68948. });
  68949. Database.prototype._checkManifestFile = function () {
  68950. var _this = this;
  68951. var noManifestFile = function () {
  68952. _this._enableSceneOffline = false;
  68953. _this._enableTexturesOffline = false;
  68954. _this.callbackManifestChecked(false);
  68955. };
  68956. var timeStampUsed = false;
  68957. var manifestURL = this.currentSceneUrl + ".manifest";
  68958. var xhr = new XMLHttpRequest();
  68959. if (navigator.onLine) {
  68960. // Adding a timestamp to by-pass browsers' cache
  68961. timeStampUsed = true;
  68962. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68963. }
  68964. xhr.open("GET", manifestURL, true);
  68965. xhr.addEventListener("load", function () {
  68966. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68967. try {
  68968. var manifestFile = JSON.parse(xhr.response);
  68969. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68970. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68971. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68972. _this.manifestVersionFound = manifestFile.version;
  68973. }
  68974. if (_this.callbackManifestChecked) {
  68975. _this.callbackManifestChecked(true);
  68976. }
  68977. }
  68978. catch (ex) {
  68979. noManifestFile();
  68980. }
  68981. }
  68982. else {
  68983. noManifestFile();
  68984. }
  68985. }, false);
  68986. xhr.addEventListener("error", function (event) {
  68987. if (timeStampUsed) {
  68988. timeStampUsed = false;
  68989. // Let's retry without the timeStamp
  68990. // It could fail when coupled with HTML5 Offline API
  68991. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68992. xhr.open("GET", retryManifestURL, true);
  68993. xhr.send();
  68994. }
  68995. else {
  68996. noManifestFile();
  68997. }
  68998. }, false);
  68999. try {
  69000. xhr.send();
  69001. }
  69002. catch (ex) {
  69003. BABYLON.Tools.Error("Error on XHR send request.");
  69004. this.callbackManifestChecked(false);
  69005. }
  69006. };
  69007. /**
  69008. * Open the database and make it available
  69009. * @param successCallback defines the callback to call on success
  69010. * @param errorCallback defines the callback to call on error
  69011. */
  69012. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69013. var _this = this;
  69014. var handleError = function () {
  69015. _this.isSupported = false;
  69016. if (errorCallback)
  69017. errorCallback();
  69018. };
  69019. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69020. // Your browser doesn't support IndexedDB
  69021. this.isSupported = false;
  69022. if (errorCallback)
  69023. errorCallback();
  69024. }
  69025. else {
  69026. // If the DB hasn't been opened or created yet
  69027. if (!this.db) {
  69028. this.hasReachedQuota = false;
  69029. this.isSupported = true;
  69030. var request = this.idbFactory.open("babylonjs", 1);
  69031. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69032. request.onerror = function (event) {
  69033. handleError();
  69034. };
  69035. // executes when a version change transaction cannot complete due to other active transactions
  69036. request.onblocked = function (event) {
  69037. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69038. handleError();
  69039. };
  69040. // DB has been opened successfully
  69041. request.onsuccess = function (event) {
  69042. _this.db = request.result;
  69043. successCallback();
  69044. };
  69045. // Initialization of the DB. Creating Scenes & Textures stores
  69046. request.onupgradeneeded = function (event) {
  69047. _this.db = (event.target).result;
  69048. if (_this.db) {
  69049. try {
  69050. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69051. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69052. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69053. }
  69054. catch (ex) {
  69055. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69056. handleError();
  69057. }
  69058. }
  69059. };
  69060. }
  69061. // DB has already been created and opened
  69062. else {
  69063. if (successCallback)
  69064. successCallback();
  69065. }
  69066. }
  69067. };
  69068. /**
  69069. * Loads an image from the database
  69070. * @param url defines the url to load from
  69071. * @param image defines the target DOM image
  69072. */
  69073. Database.prototype.loadImageFromDB = function (url, image) {
  69074. var _this = this;
  69075. var completeURL = Database._ReturnFullUrlLocation(url);
  69076. var saveAndLoadImage = function () {
  69077. if (!_this.hasReachedQuota && _this.db !== null) {
  69078. // the texture is not yet in the DB, let's try to save it
  69079. _this._saveImageIntoDBAsync(completeURL, image);
  69080. }
  69081. // If the texture is not in the DB and we've reached the DB quota limit
  69082. // let's load it directly from the web
  69083. else {
  69084. image.src = url;
  69085. }
  69086. };
  69087. if (!this.mustUpdateRessources) {
  69088. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69089. }
  69090. // First time we're download the images or update requested in the manifest file by a version change
  69091. else {
  69092. saveAndLoadImage();
  69093. }
  69094. };
  69095. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69096. if (this.isSupported && this.db !== null) {
  69097. var texture;
  69098. var transaction = this.db.transaction(["textures"]);
  69099. transaction.onabort = function (event) {
  69100. image.src = url;
  69101. };
  69102. transaction.oncomplete = function (event) {
  69103. var blobTextureURL;
  69104. if (texture) {
  69105. var URL = window.URL || window.webkitURL;
  69106. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69107. image.onerror = function () {
  69108. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69109. image.src = url;
  69110. };
  69111. image.src = blobTextureURL;
  69112. }
  69113. else {
  69114. notInDBCallback();
  69115. }
  69116. };
  69117. var getRequest = transaction.objectStore("textures").get(url);
  69118. getRequest.onsuccess = function (event) {
  69119. texture = (event.target).result;
  69120. };
  69121. getRequest.onerror = function (event) {
  69122. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69123. image.src = url;
  69124. };
  69125. }
  69126. else {
  69127. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69128. image.src = url;
  69129. }
  69130. };
  69131. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69132. var _this = this;
  69133. if (this.isSupported) {
  69134. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69135. var generateBlobUrl = function () {
  69136. var blobTextureURL;
  69137. if (blob) {
  69138. var URL = window.URL || window.webkitURL;
  69139. try {
  69140. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69141. }
  69142. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69143. catch (ex) {
  69144. blobTextureURL = URL.createObjectURL(blob);
  69145. }
  69146. }
  69147. if (blobTextureURL) {
  69148. image.src = blobTextureURL;
  69149. }
  69150. };
  69151. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69152. var xhr = new XMLHttpRequest(), blob;
  69153. xhr.open("GET", url, true);
  69154. xhr.responseType = "blob";
  69155. xhr.addEventListener("load", function () {
  69156. if (xhr.status === 200 && _this.db) {
  69157. // Blob as response (XHR2)
  69158. blob = xhr.response;
  69159. var transaction = _this.db.transaction(["textures"], "readwrite");
  69160. // the transaction could abort because of a QuotaExceededError error
  69161. transaction.onabort = function (event) {
  69162. try {
  69163. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69164. var srcElement = (event.srcElement || event.target);
  69165. var error = srcElement.error;
  69166. if (error && error.name === "QuotaExceededError") {
  69167. _this.hasReachedQuota = true;
  69168. }
  69169. }
  69170. catch (ex) { }
  69171. generateBlobUrl();
  69172. };
  69173. transaction.oncomplete = function (event) {
  69174. generateBlobUrl();
  69175. };
  69176. var newTexture = { textureUrl: url, data: blob };
  69177. try {
  69178. // Put the blob into the dabase
  69179. var addRequest = transaction.objectStore("textures").put(newTexture);
  69180. addRequest.onsuccess = function (event) {
  69181. };
  69182. addRequest.onerror = function (event) {
  69183. generateBlobUrl();
  69184. };
  69185. }
  69186. catch (ex) {
  69187. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69188. if (ex.code === 25) {
  69189. Database.IsUASupportingBlobStorage = false;
  69190. }
  69191. image.src = url;
  69192. }
  69193. }
  69194. else {
  69195. image.src = url;
  69196. }
  69197. }, false);
  69198. xhr.addEventListener("error", function (event) {
  69199. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69200. image.src = url;
  69201. }, false);
  69202. xhr.send();
  69203. }
  69204. else {
  69205. image.src = url;
  69206. }
  69207. }
  69208. else {
  69209. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69210. image.src = url;
  69211. }
  69212. };
  69213. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69214. var _this = this;
  69215. var updateVersion = function () {
  69216. // the version is not yet in the DB or we need to update it
  69217. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69218. };
  69219. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69220. };
  69221. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69222. var _this = this;
  69223. if (this.isSupported && this.db) {
  69224. var version;
  69225. try {
  69226. var transaction = this.db.transaction(["versions"]);
  69227. transaction.oncomplete = function (event) {
  69228. if (version) {
  69229. // If the version in the JSON file is different from the version in DB
  69230. if (_this.manifestVersionFound !== version.data) {
  69231. _this.mustUpdateRessources = true;
  69232. updateInDBCallback();
  69233. }
  69234. else {
  69235. callback(version.data);
  69236. }
  69237. }
  69238. // version was not found in DB
  69239. else {
  69240. _this.mustUpdateRessources = true;
  69241. updateInDBCallback();
  69242. }
  69243. };
  69244. transaction.onabort = function (event) {
  69245. callback(-1);
  69246. };
  69247. var getRequest = transaction.objectStore("versions").get(url);
  69248. getRequest.onsuccess = function (event) {
  69249. version = (event.target).result;
  69250. };
  69251. getRequest.onerror = function (event) {
  69252. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69253. callback(-1);
  69254. };
  69255. }
  69256. catch (ex) {
  69257. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69258. callback(-1);
  69259. }
  69260. }
  69261. else {
  69262. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69263. callback(-1);
  69264. }
  69265. };
  69266. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69267. var _this = this;
  69268. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69269. try {
  69270. // Open a transaction to the database
  69271. var transaction = this.db.transaction(["versions"], "readwrite");
  69272. // the transaction could abort because of a QuotaExceededError error
  69273. transaction.onabort = function (event) {
  69274. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69275. var error = event.srcElement['error'];
  69276. if (error && error.name === "QuotaExceededError") {
  69277. _this.hasReachedQuota = true;
  69278. }
  69279. }
  69280. catch (ex) { }
  69281. callback(-1);
  69282. };
  69283. transaction.oncomplete = function (event) {
  69284. callback(_this.manifestVersionFound);
  69285. };
  69286. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69287. // Put the scene into the database
  69288. var addRequest = transaction.objectStore("versions").put(newVersion);
  69289. addRequest.onsuccess = function (event) {
  69290. };
  69291. addRequest.onerror = function (event) {
  69292. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69293. };
  69294. }
  69295. catch (ex) {
  69296. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69297. callback(-1);
  69298. }
  69299. }
  69300. else {
  69301. callback(-1);
  69302. }
  69303. };
  69304. /**
  69305. * Loads a file from database
  69306. * @param url defines the URL to load from
  69307. * @param sceneLoaded defines a callback to call on success
  69308. * @param progressCallBack defines a callback to call when progress changed
  69309. * @param errorCallback defines a callback to call on error
  69310. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69311. */
  69312. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69313. var _this = this;
  69314. var completeUrl = Database._ReturnFullUrlLocation(url);
  69315. var saveAndLoadFile = function () {
  69316. // the scene is not yet in the DB, let's try to save it
  69317. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69318. };
  69319. this._checkVersionFromDB(completeUrl, function (version) {
  69320. if (version !== -1) {
  69321. if (!_this.mustUpdateRessources) {
  69322. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69323. }
  69324. else {
  69325. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69326. }
  69327. }
  69328. else {
  69329. if (errorCallback) {
  69330. errorCallback();
  69331. }
  69332. }
  69333. });
  69334. };
  69335. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69336. if (this.isSupported && this.db) {
  69337. var targetStore;
  69338. if (url.indexOf(".babylon") !== -1) {
  69339. targetStore = "scenes";
  69340. }
  69341. else {
  69342. targetStore = "textures";
  69343. }
  69344. var file;
  69345. var transaction = this.db.transaction([targetStore]);
  69346. transaction.oncomplete = function (event) {
  69347. if (file) {
  69348. callback(file.data);
  69349. }
  69350. // file was not found in DB
  69351. else {
  69352. notInDBCallback();
  69353. }
  69354. };
  69355. transaction.onabort = function (event) {
  69356. notInDBCallback();
  69357. };
  69358. var getRequest = transaction.objectStore(targetStore).get(url);
  69359. getRequest.onsuccess = function (event) {
  69360. file = (event.target).result;
  69361. };
  69362. getRequest.onerror = function (event) {
  69363. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69364. notInDBCallback();
  69365. };
  69366. }
  69367. else {
  69368. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69369. callback();
  69370. }
  69371. };
  69372. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69373. var _this = this;
  69374. if (this.isSupported) {
  69375. var targetStore;
  69376. if (url.indexOf(".babylon") !== -1) {
  69377. targetStore = "scenes";
  69378. }
  69379. else {
  69380. targetStore = "textures";
  69381. }
  69382. // Create XHR
  69383. var xhr = new XMLHttpRequest();
  69384. var fileData;
  69385. xhr.open("GET", url, true);
  69386. if (useArrayBuffer) {
  69387. xhr.responseType = "arraybuffer";
  69388. }
  69389. if (progressCallback) {
  69390. xhr.onprogress = progressCallback;
  69391. }
  69392. xhr.addEventListener("load", function () {
  69393. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69394. // Blob as response (XHR2)
  69395. //fileData = xhr.responseText;
  69396. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69397. if (!_this.hasReachedQuota && _this.db) {
  69398. // Open a transaction to the database
  69399. var transaction = _this.db.transaction([targetStore], "readwrite");
  69400. // the transaction could abort because of a QuotaExceededError error
  69401. transaction.onabort = function (event) {
  69402. try {
  69403. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69404. var error = event.srcElement['error'];
  69405. if (error && error.name === "QuotaExceededError") {
  69406. _this.hasReachedQuota = true;
  69407. }
  69408. }
  69409. catch (ex) { }
  69410. callback(fileData);
  69411. };
  69412. transaction.oncomplete = function (event) {
  69413. callback(fileData);
  69414. };
  69415. var newFile;
  69416. if (targetStore === "scenes") {
  69417. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69418. }
  69419. else {
  69420. newFile = { textureUrl: url, data: fileData };
  69421. }
  69422. try {
  69423. // Put the scene into the database
  69424. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69425. addRequest.onsuccess = function (event) {
  69426. };
  69427. addRequest.onerror = function (event) {
  69428. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69429. };
  69430. }
  69431. catch (ex) {
  69432. callback(fileData);
  69433. }
  69434. }
  69435. else {
  69436. callback(fileData);
  69437. }
  69438. }
  69439. else {
  69440. callback();
  69441. }
  69442. }, false);
  69443. xhr.addEventListener("error", function (event) {
  69444. BABYLON.Tools.Error("error on XHR request.");
  69445. callback();
  69446. }, false);
  69447. xhr.send();
  69448. }
  69449. else {
  69450. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69451. callback();
  69452. }
  69453. };
  69454. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69455. Database.IsUASupportingBlobStorage = true;
  69456. /** Gets a boolean indicating if Database storate is enabled */
  69457. Database.IDBStorageEnabled = true;
  69458. Database._ParseURL = function (url) {
  69459. var a = document.createElement('a');
  69460. a.href = url;
  69461. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69462. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69463. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69464. return absLocation;
  69465. };
  69466. Database._ReturnFullUrlLocation = function (url) {
  69467. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69468. return (Database._ParseURL(window.location.href) + url);
  69469. }
  69470. else {
  69471. return url;
  69472. }
  69473. };
  69474. return Database;
  69475. }());
  69476. BABYLON.Database = Database;
  69477. })(BABYLON || (BABYLON = {}));
  69478. //# sourceMappingURL=babylon.database.js.map
  69479. var BABYLON;
  69480. (function (BABYLON) {
  69481. var FresnelParameters = /** @class */ (function () {
  69482. function FresnelParameters() {
  69483. this._isEnabled = true;
  69484. this.leftColor = BABYLON.Color3.White();
  69485. this.rightColor = BABYLON.Color3.Black();
  69486. this.bias = 0;
  69487. this.power = 1;
  69488. }
  69489. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69490. get: function () {
  69491. return this._isEnabled;
  69492. },
  69493. set: function (value) {
  69494. if (this._isEnabled === value) {
  69495. return;
  69496. }
  69497. this._isEnabled = value;
  69498. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69499. },
  69500. enumerable: true,
  69501. configurable: true
  69502. });
  69503. FresnelParameters.prototype.clone = function () {
  69504. var newFresnelParameters = new FresnelParameters();
  69505. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69506. return newFresnelParameters;
  69507. };
  69508. FresnelParameters.prototype.serialize = function () {
  69509. var serializationObject = {};
  69510. serializationObject.isEnabled = this.isEnabled;
  69511. serializationObject.leftColor = this.leftColor.asArray();
  69512. serializationObject.rightColor = this.rightColor.asArray();
  69513. serializationObject.bias = this.bias;
  69514. serializationObject.power = this.power;
  69515. return serializationObject;
  69516. };
  69517. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69518. var fresnelParameters = new FresnelParameters();
  69519. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69520. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69521. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69522. fresnelParameters.bias = parsedFresnelParameters.bias;
  69523. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69524. return fresnelParameters;
  69525. };
  69526. return FresnelParameters;
  69527. }());
  69528. BABYLON.FresnelParameters = FresnelParameters;
  69529. })(BABYLON || (BABYLON = {}));
  69530. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69531. var BABYLON;
  69532. (function (BABYLON) {
  69533. var MultiMaterial = /** @class */ (function (_super) {
  69534. __extends(MultiMaterial, _super);
  69535. function MultiMaterial(name, scene) {
  69536. var _this = _super.call(this, name, scene, true) || this;
  69537. scene.multiMaterials.push(_this);
  69538. _this.subMaterials = new Array();
  69539. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69540. return _this;
  69541. }
  69542. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69543. get: function () {
  69544. return this._subMaterials;
  69545. },
  69546. set: function (value) {
  69547. this._subMaterials = value;
  69548. this._hookArray(value);
  69549. },
  69550. enumerable: true,
  69551. configurable: true
  69552. });
  69553. MultiMaterial.prototype._hookArray = function (array) {
  69554. var _this = this;
  69555. var oldPush = array.push;
  69556. array.push = function () {
  69557. var items = [];
  69558. for (var _i = 0; _i < arguments.length; _i++) {
  69559. items[_i] = arguments[_i];
  69560. }
  69561. var result = oldPush.apply(array, items);
  69562. _this._markAllSubMeshesAsTexturesDirty();
  69563. return result;
  69564. };
  69565. var oldSplice = array.splice;
  69566. array.splice = function (index, deleteCount) {
  69567. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69568. _this._markAllSubMeshesAsTexturesDirty();
  69569. return deleted;
  69570. };
  69571. };
  69572. // Properties
  69573. MultiMaterial.prototype.getSubMaterial = function (index) {
  69574. if (index < 0 || index >= this.subMaterials.length) {
  69575. return this.getScene().defaultMaterial;
  69576. }
  69577. return this.subMaterials[index];
  69578. };
  69579. MultiMaterial.prototype.getActiveTextures = function () {
  69580. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69581. if (subMaterial) {
  69582. return subMaterial.getActiveTextures();
  69583. }
  69584. else {
  69585. return [];
  69586. }
  69587. }));
  69588. var _a;
  69589. };
  69590. // Methods
  69591. MultiMaterial.prototype.getClassName = function () {
  69592. return "MultiMaterial";
  69593. };
  69594. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69595. for (var index = 0; index < this.subMaterials.length; index++) {
  69596. var subMaterial = this.subMaterials[index];
  69597. if (subMaterial) {
  69598. if (subMaterial.storeEffectOnSubMeshes) {
  69599. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69600. return false;
  69601. }
  69602. continue;
  69603. }
  69604. if (!subMaterial.isReady(mesh)) {
  69605. return false;
  69606. }
  69607. }
  69608. }
  69609. return true;
  69610. };
  69611. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69612. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69613. for (var index = 0; index < this.subMaterials.length; index++) {
  69614. var subMaterial = null;
  69615. var current = this.subMaterials[index];
  69616. if (cloneChildren && current) {
  69617. subMaterial = current.clone(name + "-" + current.name);
  69618. }
  69619. else {
  69620. subMaterial = this.subMaterials[index];
  69621. }
  69622. newMultiMaterial.subMaterials.push(subMaterial);
  69623. }
  69624. return newMultiMaterial;
  69625. };
  69626. MultiMaterial.prototype.serialize = function () {
  69627. var serializationObject = {};
  69628. serializationObject.name = this.name;
  69629. serializationObject.id = this.id;
  69630. if (BABYLON.Tags) {
  69631. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69632. }
  69633. serializationObject.materials = [];
  69634. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69635. var subMat = this.subMaterials[matIndex];
  69636. if (subMat) {
  69637. serializationObject.materials.push(subMat.id);
  69638. }
  69639. else {
  69640. serializationObject.materials.push(null);
  69641. }
  69642. }
  69643. return serializationObject;
  69644. };
  69645. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69646. var scene = this.getScene();
  69647. if (!scene) {
  69648. return;
  69649. }
  69650. var index = scene.multiMaterials.indexOf(this);
  69651. if (index >= 0) {
  69652. scene.multiMaterials.splice(index, 1);
  69653. }
  69654. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69655. };
  69656. return MultiMaterial;
  69657. }(BABYLON.Material));
  69658. BABYLON.MultiMaterial = MultiMaterial;
  69659. })(BABYLON || (BABYLON = {}));
  69660. //# sourceMappingURL=babylon.multiMaterial.js.map
  69661. var BABYLON;
  69662. (function (BABYLON) {
  69663. var FreeCameraTouchInput = /** @class */ (function () {
  69664. function FreeCameraTouchInput() {
  69665. this._offsetX = null;
  69666. this._offsetY = null;
  69667. this._pointerPressed = new Array();
  69668. this.touchAngularSensibility = 200000.0;
  69669. this.touchMoveSensibility = 250.0;
  69670. }
  69671. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69672. var _this = this;
  69673. var previousPosition = null;
  69674. if (this._pointerInput === undefined) {
  69675. this._onLostFocus = function (evt) {
  69676. _this._offsetX = null;
  69677. _this._offsetY = null;
  69678. };
  69679. this._pointerInput = function (p, s) {
  69680. var evt = p.event;
  69681. if (evt.pointerType === "mouse") {
  69682. return;
  69683. }
  69684. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69685. if (!noPreventDefault) {
  69686. evt.preventDefault();
  69687. }
  69688. _this._pointerPressed.push(evt.pointerId);
  69689. if (_this._pointerPressed.length !== 1) {
  69690. return;
  69691. }
  69692. previousPosition = {
  69693. x: evt.clientX,
  69694. y: evt.clientY
  69695. };
  69696. }
  69697. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69698. if (!noPreventDefault) {
  69699. evt.preventDefault();
  69700. }
  69701. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69702. if (index === -1) {
  69703. return;
  69704. }
  69705. _this._pointerPressed.splice(index, 1);
  69706. if (index != 0) {
  69707. return;
  69708. }
  69709. previousPosition = null;
  69710. _this._offsetX = null;
  69711. _this._offsetY = null;
  69712. }
  69713. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69714. if (!noPreventDefault) {
  69715. evt.preventDefault();
  69716. }
  69717. if (!previousPosition) {
  69718. return;
  69719. }
  69720. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69721. if (index != 0) {
  69722. return;
  69723. }
  69724. _this._offsetX = evt.clientX - previousPosition.x;
  69725. _this._offsetY = -(evt.clientY - previousPosition.y);
  69726. }
  69727. };
  69728. }
  69729. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69730. if (this._onLostFocus) {
  69731. element.addEventListener("blur", this._onLostFocus);
  69732. }
  69733. };
  69734. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69735. if (this._pointerInput && element) {
  69736. if (this._observer) {
  69737. this.camera.getScene().onPointerObservable.remove(this._observer);
  69738. this._observer = null;
  69739. }
  69740. if (this._onLostFocus) {
  69741. element.removeEventListener("blur", this._onLostFocus);
  69742. this._onLostFocus = null;
  69743. }
  69744. this._pointerPressed = [];
  69745. this._offsetX = null;
  69746. this._offsetY = null;
  69747. }
  69748. };
  69749. FreeCameraTouchInput.prototype.checkInputs = function () {
  69750. if (this._offsetX && this._offsetY) {
  69751. var camera = this.camera;
  69752. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69753. if (this._pointerPressed.length > 1) {
  69754. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69755. }
  69756. else {
  69757. var speed = camera._computeLocalCameraSpeed();
  69758. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69759. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69760. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69761. }
  69762. }
  69763. };
  69764. FreeCameraTouchInput.prototype.getClassName = function () {
  69765. return "FreeCameraTouchInput";
  69766. };
  69767. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69768. return "touch";
  69769. };
  69770. __decorate([
  69771. BABYLON.serialize()
  69772. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69773. __decorate([
  69774. BABYLON.serialize()
  69775. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69776. return FreeCameraTouchInput;
  69777. }());
  69778. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69779. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69780. })(BABYLON || (BABYLON = {}));
  69781. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69782. var BABYLON;
  69783. (function (BABYLON) {
  69784. // We're mainly based on the logic defined into the FreeCamera code
  69785. var TouchCamera = /** @class */ (function (_super) {
  69786. __extends(TouchCamera, _super);
  69787. //-- end properties for backward compatibility for inputs
  69788. function TouchCamera(name, position, scene) {
  69789. var _this = _super.call(this, name, position, scene) || this;
  69790. _this.inputs.addTouch();
  69791. _this._setupInputs();
  69792. return _this;
  69793. }
  69794. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69795. //-- Begin properties for backward compatibility for inputs
  69796. get: function () {
  69797. var touch = this.inputs.attached["touch"];
  69798. if (touch)
  69799. return touch.touchAngularSensibility;
  69800. return 0;
  69801. },
  69802. set: function (value) {
  69803. var touch = this.inputs.attached["touch"];
  69804. if (touch)
  69805. touch.touchAngularSensibility = value;
  69806. },
  69807. enumerable: true,
  69808. configurable: true
  69809. });
  69810. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69811. get: function () {
  69812. var touch = this.inputs.attached["touch"];
  69813. if (touch)
  69814. return touch.touchMoveSensibility;
  69815. return 0;
  69816. },
  69817. set: function (value) {
  69818. var touch = this.inputs.attached["touch"];
  69819. if (touch)
  69820. touch.touchMoveSensibility = value;
  69821. },
  69822. enumerable: true,
  69823. configurable: true
  69824. });
  69825. TouchCamera.prototype.getClassName = function () {
  69826. return "TouchCamera";
  69827. };
  69828. TouchCamera.prototype._setupInputs = function () {
  69829. var mouse = this.inputs.attached["mouse"];
  69830. if (mouse) {
  69831. mouse.touchEnabled = false;
  69832. }
  69833. };
  69834. return TouchCamera;
  69835. }(BABYLON.FreeCamera));
  69836. BABYLON.TouchCamera = TouchCamera;
  69837. })(BABYLON || (BABYLON = {}));
  69838. //# sourceMappingURL=babylon.touchCamera.js.map
  69839. var BABYLON;
  69840. (function (BABYLON) {
  69841. var ProceduralTexture = /** @class */ (function (_super) {
  69842. __extends(ProceduralTexture, _super);
  69843. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69844. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69845. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69846. if (isCube === void 0) { isCube = false; }
  69847. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69848. _this.isCube = isCube;
  69849. _this.isEnabled = true;
  69850. _this._currentRefreshId = -1;
  69851. _this._refreshRate = 1;
  69852. _this._vertexBuffers = {};
  69853. _this._uniforms = new Array();
  69854. _this._samplers = new Array();
  69855. _this._textures = {};
  69856. _this._floats = {};
  69857. _this._floatsArrays = {};
  69858. _this._colors3 = {};
  69859. _this._colors4 = {};
  69860. _this._vectors2 = {};
  69861. _this._vectors3 = {};
  69862. _this._matrices = {};
  69863. _this._fallbackTextureUsed = false;
  69864. scene.proceduralTextures.push(_this);
  69865. _this._engine = scene.getEngine();
  69866. _this.name = name;
  69867. _this.isRenderTarget = true;
  69868. _this._size = size;
  69869. _this._generateMipMaps = generateMipMaps;
  69870. _this.setFragment(fragment);
  69871. _this._fallbackTexture = fallbackTexture;
  69872. if (isCube) {
  69873. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69874. _this.setFloat("face", 0);
  69875. }
  69876. else {
  69877. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69878. }
  69879. // VBO
  69880. var vertices = [];
  69881. vertices.push(1, 1);
  69882. vertices.push(-1, 1);
  69883. vertices.push(-1, -1);
  69884. vertices.push(1, -1);
  69885. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69886. _this._createIndexBuffer();
  69887. return _this;
  69888. }
  69889. ProceduralTexture.prototype._createIndexBuffer = function () {
  69890. var engine = this._engine;
  69891. // Indices
  69892. var indices = [];
  69893. indices.push(0);
  69894. indices.push(1);
  69895. indices.push(2);
  69896. indices.push(0);
  69897. indices.push(2);
  69898. indices.push(3);
  69899. this._indexBuffer = engine.createIndexBuffer(indices);
  69900. };
  69901. ProceduralTexture.prototype._rebuild = function () {
  69902. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69903. if (vb) {
  69904. vb._rebuild();
  69905. }
  69906. this._createIndexBuffer();
  69907. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69908. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69909. }
  69910. };
  69911. ProceduralTexture.prototype.reset = function () {
  69912. if (this._effect === undefined) {
  69913. return;
  69914. }
  69915. var engine = this._engine;
  69916. engine._releaseEffect(this._effect);
  69917. };
  69918. ProceduralTexture.prototype.isReady = function () {
  69919. var _this = this;
  69920. var engine = this._engine;
  69921. var shaders;
  69922. if (!this._fragment) {
  69923. return false;
  69924. }
  69925. if (this._fallbackTextureUsed) {
  69926. return true;
  69927. }
  69928. if (this._fragment.fragmentElement !== undefined) {
  69929. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69930. }
  69931. else {
  69932. shaders = { vertex: "procedural", fragment: this._fragment };
  69933. }
  69934. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69935. _this.releaseInternalTexture();
  69936. if (_this._fallbackTexture) {
  69937. _this._texture = _this._fallbackTexture._texture;
  69938. if (_this._texture) {
  69939. _this._texture.incrementReferences();
  69940. }
  69941. }
  69942. _this._fallbackTextureUsed = true;
  69943. });
  69944. return this._effect.isReady();
  69945. };
  69946. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69947. this._currentRefreshId = -1;
  69948. };
  69949. ProceduralTexture.prototype.setFragment = function (fragment) {
  69950. this._fragment = fragment;
  69951. };
  69952. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69953. get: function () {
  69954. return this._refreshRate;
  69955. },
  69956. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69957. set: function (value) {
  69958. this._refreshRate = value;
  69959. this.resetRefreshCounter();
  69960. },
  69961. enumerable: true,
  69962. configurable: true
  69963. });
  69964. ProceduralTexture.prototype._shouldRender = function () {
  69965. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69966. return false;
  69967. }
  69968. if (this._fallbackTextureUsed) {
  69969. return false;
  69970. }
  69971. if (this._currentRefreshId === -1) { // At least render once
  69972. this._currentRefreshId = 1;
  69973. return true;
  69974. }
  69975. if (this.refreshRate === this._currentRefreshId) {
  69976. this._currentRefreshId = 1;
  69977. return true;
  69978. }
  69979. this._currentRefreshId++;
  69980. return false;
  69981. };
  69982. ProceduralTexture.prototype.getRenderSize = function () {
  69983. return this._size;
  69984. };
  69985. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69986. if (this._fallbackTextureUsed) {
  69987. return;
  69988. }
  69989. this.releaseInternalTexture();
  69990. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69991. // Update properties
  69992. this._size = size;
  69993. this._generateMipMaps = generateMipMaps;
  69994. };
  69995. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69996. if (this._uniforms.indexOf(uniformName) === -1) {
  69997. this._uniforms.push(uniformName);
  69998. }
  69999. };
  70000. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70001. if (this._samplers.indexOf(name) === -1) {
  70002. this._samplers.push(name);
  70003. }
  70004. this._textures[name] = texture;
  70005. return this;
  70006. };
  70007. ProceduralTexture.prototype.setFloat = function (name, value) {
  70008. this._checkUniform(name);
  70009. this._floats[name] = value;
  70010. return this;
  70011. };
  70012. ProceduralTexture.prototype.setFloats = function (name, value) {
  70013. this._checkUniform(name);
  70014. this._floatsArrays[name] = value;
  70015. return this;
  70016. };
  70017. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70018. this._checkUniform(name);
  70019. this._colors3[name] = value;
  70020. return this;
  70021. };
  70022. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70023. this._checkUniform(name);
  70024. this._colors4[name] = value;
  70025. return this;
  70026. };
  70027. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70028. this._checkUniform(name);
  70029. this._vectors2[name] = value;
  70030. return this;
  70031. };
  70032. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70033. this._checkUniform(name);
  70034. this._vectors3[name] = value;
  70035. return this;
  70036. };
  70037. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70038. this._checkUniform(name);
  70039. this._matrices[name] = value;
  70040. return this;
  70041. };
  70042. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70043. var scene = this.getScene();
  70044. if (!scene) {
  70045. return;
  70046. }
  70047. var engine = this._engine;
  70048. // Render
  70049. engine.enableEffect(this._effect);
  70050. engine.setState(false);
  70051. // Texture
  70052. for (var name in this._textures) {
  70053. this._effect.setTexture(name, this._textures[name]);
  70054. }
  70055. // Float
  70056. for (name in this._floats) {
  70057. this._effect.setFloat(name, this._floats[name]);
  70058. }
  70059. // Floats
  70060. for (name in this._floatsArrays) {
  70061. this._effect.setArray(name, this._floatsArrays[name]);
  70062. }
  70063. // Color3
  70064. for (name in this._colors3) {
  70065. this._effect.setColor3(name, this._colors3[name]);
  70066. }
  70067. // Color4
  70068. for (name in this._colors4) {
  70069. var color = this._colors4[name];
  70070. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70071. }
  70072. // Vector2
  70073. for (name in this._vectors2) {
  70074. this._effect.setVector2(name, this._vectors2[name]);
  70075. }
  70076. // Vector3
  70077. for (name in this._vectors3) {
  70078. this._effect.setVector3(name, this._vectors3[name]);
  70079. }
  70080. // Matrix
  70081. for (name in this._matrices) {
  70082. this._effect.setMatrix(name, this._matrices[name]);
  70083. }
  70084. if (!this._texture) {
  70085. return;
  70086. }
  70087. if (this.isCube) {
  70088. for (var face = 0; face < 6; face++) {
  70089. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70090. // VBOs
  70091. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70092. this._effect.setFloat("face", face);
  70093. // Clear
  70094. engine.clear(scene.clearColor, true, true, true);
  70095. // Draw order
  70096. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70097. // Mipmaps
  70098. if (face === 5) {
  70099. engine.generateMipMapsForCubemap(this._texture);
  70100. }
  70101. }
  70102. }
  70103. else {
  70104. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70105. // VBOs
  70106. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70107. // Clear
  70108. engine.clear(scene.clearColor, true, true, true);
  70109. // Draw order
  70110. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70111. }
  70112. // Unbind
  70113. engine.unBindFramebuffer(this._texture, this.isCube);
  70114. if (this.onGenerated) {
  70115. this.onGenerated();
  70116. }
  70117. };
  70118. ProceduralTexture.prototype.clone = function () {
  70119. var textureSize = this.getSize();
  70120. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70121. // Base texture
  70122. newTexture.hasAlpha = this.hasAlpha;
  70123. newTexture.level = this.level;
  70124. // RenderTarget Texture
  70125. newTexture.coordinatesMode = this.coordinatesMode;
  70126. return newTexture;
  70127. };
  70128. ProceduralTexture.prototype.dispose = function () {
  70129. var scene = this.getScene();
  70130. if (!scene) {
  70131. return;
  70132. }
  70133. var index = scene.proceduralTextures.indexOf(this);
  70134. if (index >= 0) {
  70135. scene.proceduralTextures.splice(index, 1);
  70136. }
  70137. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70138. if (vertexBuffer) {
  70139. vertexBuffer.dispose();
  70140. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70141. }
  70142. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70143. this._indexBuffer = null;
  70144. }
  70145. _super.prototype.dispose.call(this);
  70146. };
  70147. __decorate([
  70148. BABYLON.serialize()
  70149. ], ProceduralTexture.prototype, "_size", void 0);
  70150. __decorate([
  70151. BABYLON.serialize()
  70152. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  70153. __decorate([
  70154. BABYLON.serialize()
  70155. ], ProceduralTexture.prototype, "isEnabled", void 0);
  70156. __decorate([
  70157. BABYLON.serialize()
  70158. ], ProceduralTexture.prototype, "refreshRate", null);
  70159. return ProceduralTexture;
  70160. }(BABYLON.Texture));
  70161. BABYLON.ProceduralTexture = ProceduralTexture;
  70162. })(BABYLON || (BABYLON = {}));
  70163. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70164. var BABYLON;
  70165. (function (BABYLON) {
  70166. var CustomProceduralTexture = /** @class */ (function (_super) {
  70167. __extends(CustomProceduralTexture, _super);
  70168. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70169. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70170. _this._animate = true;
  70171. _this._time = 0;
  70172. _this._texturePath = texturePath;
  70173. //Try to load json
  70174. _this.loadJson(texturePath);
  70175. _this.refreshRate = 1;
  70176. return _this;
  70177. }
  70178. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70179. var _this = this;
  70180. var noConfigFile = function () {
  70181. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70182. try {
  70183. _this.setFragment(_this._texturePath);
  70184. }
  70185. catch (ex) {
  70186. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70187. }
  70188. };
  70189. var configFileUrl = jsonUrl + "/config.json";
  70190. var xhr = new XMLHttpRequest();
  70191. xhr.open("GET", configFileUrl, true);
  70192. xhr.addEventListener("load", function () {
  70193. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70194. try {
  70195. _this._config = JSON.parse(xhr.response);
  70196. _this.updateShaderUniforms();
  70197. _this.updateTextures();
  70198. _this.setFragment(_this._texturePath + "/custom");
  70199. _this._animate = _this._config.animate;
  70200. _this.refreshRate = _this._config.refreshrate;
  70201. }
  70202. catch (ex) {
  70203. noConfigFile();
  70204. }
  70205. }
  70206. else {
  70207. noConfigFile();
  70208. }
  70209. }, false);
  70210. xhr.addEventListener("error", function () {
  70211. noConfigFile();
  70212. }, false);
  70213. try {
  70214. xhr.send();
  70215. }
  70216. catch (ex) {
  70217. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70218. }
  70219. };
  70220. CustomProceduralTexture.prototype.isReady = function () {
  70221. if (!_super.prototype.isReady.call(this)) {
  70222. return false;
  70223. }
  70224. for (var name in this._textures) {
  70225. var texture = this._textures[name];
  70226. if (!texture.isReady()) {
  70227. return false;
  70228. }
  70229. }
  70230. return true;
  70231. };
  70232. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70233. var scene = this.getScene();
  70234. if (this._animate && scene) {
  70235. this._time += scene.getAnimationRatio() * 0.03;
  70236. this.updateShaderUniforms();
  70237. }
  70238. _super.prototype.render.call(this, useCameraPostProcess);
  70239. };
  70240. CustomProceduralTexture.prototype.updateTextures = function () {
  70241. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70242. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70243. }
  70244. };
  70245. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70246. if (this._config) {
  70247. for (var j = 0; j < this._config.uniforms.length; j++) {
  70248. var uniform = this._config.uniforms[j];
  70249. switch (uniform.type) {
  70250. case "float":
  70251. this.setFloat(uniform.name, uniform.value);
  70252. break;
  70253. case "color3":
  70254. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70255. break;
  70256. case "color4":
  70257. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70258. break;
  70259. case "vector2":
  70260. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70261. break;
  70262. case "vector3":
  70263. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70264. break;
  70265. }
  70266. }
  70267. }
  70268. this.setFloat("time", this._time);
  70269. };
  70270. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70271. get: function () {
  70272. return this._animate;
  70273. },
  70274. set: function (value) {
  70275. this._animate = value;
  70276. },
  70277. enumerable: true,
  70278. configurable: true
  70279. });
  70280. return CustomProceduralTexture;
  70281. }(BABYLON.ProceduralTexture));
  70282. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70283. })(BABYLON || (BABYLON = {}));
  70284. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70285. var BABYLON;
  70286. (function (BABYLON) {
  70287. var FreeCameraGamepadInput = /** @class */ (function () {
  70288. function FreeCameraGamepadInput() {
  70289. this.gamepadAngularSensibility = 200;
  70290. this.gamepadMoveSensibility = 40;
  70291. // private members
  70292. this._cameraTransform = BABYLON.Matrix.Identity();
  70293. this._deltaTransform = BABYLON.Vector3.Zero();
  70294. this._vector3 = BABYLON.Vector3.Zero();
  70295. this._vector2 = BABYLON.Vector2.Zero();
  70296. }
  70297. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70298. var _this = this;
  70299. var manager = this.camera.getScene().gamepadManager;
  70300. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70301. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70302. // prioritize XBOX gamepads.
  70303. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70304. _this.gamepad = gamepad;
  70305. }
  70306. }
  70307. });
  70308. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70309. if (_this.gamepad === gamepad) {
  70310. _this.gamepad = null;
  70311. }
  70312. });
  70313. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70314. };
  70315. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70316. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70317. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70318. this.gamepad = null;
  70319. };
  70320. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70321. if (this.gamepad && this.gamepad.leftStick) {
  70322. var camera = this.camera;
  70323. var LSValues = this.gamepad.leftStick;
  70324. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70325. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70326. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70327. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70328. var RSValues = this.gamepad.rightStick;
  70329. if (RSValues) {
  70330. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70331. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70332. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70333. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70334. }
  70335. else {
  70336. RSValues = { x: 0, y: 0 };
  70337. }
  70338. if (!camera.rotationQuaternion) {
  70339. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70340. }
  70341. else {
  70342. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70343. }
  70344. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70345. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70346. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70347. camera.cameraDirection.addInPlace(this._deltaTransform);
  70348. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70349. camera.cameraRotation.addInPlace(this._vector2);
  70350. }
  70351. };
  70352. FreeCameraGamepadInput.prototype.getClassName = function () {
  70353. return "FreeCameraGamepadInput";
  70354. };
  70355. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70356. return "gamepad";
  70357. };
  70358. __decorate([
  70359. BABYLON.serialize()
  70360. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70361. __decorate([
  70362. BABYLON.serialize()
  70363. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70364. return FreeCameraGamepadInput;
  70365. }());
  70366. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70367. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70368. })(BABYLON || (BABYLON = {}));
  70369. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70370. var BABYLON;
  70371. (function (BABYLON) {
  70372. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70373. function ArcRotateCameraGamepadInput() {
  70374. this.gamepadRotationSensibility = 80;
  70375. this.gamepadMoveSensibility = 40;
  70376. }
  70377. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70378. var _this = this;
  70379. var manager = this.camera.getScene().gamepadManager;
  70380. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70381. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70382. // prioritize XBOX gamepads.
  70383. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70384. _this.gamepad = gamepad;
  70385. }
  70386. }
  70387. });
  70388. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70389. if (_this.gamepad === gamepad) {
  70390. _this.gamepad = null;
  70391. }
  70392. });
  70393. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70394. };
  70395. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70396. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70397. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70398. this.gamepad = null;
  70399. };
  70400. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70401. if (this.gamepad) {
  70402. var camera = this.camera;
  70403. var RSValues = this.gamepad.rightStick;
  70404. if (RSValues) {
  70405. if (RSValues.x != 0) {
  70406. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70407. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70408. camera.inertialAlphaOffset += normalizedRX;
  70409. }
  70410. }
  70411. if (RSValues.y != 0) {
  70412. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70413. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70414. camera.inertialBetaOffset += normalizedRY;
  70415. }
  70416. }
  70417. }
  70418. var LSValues = this.gamepad.leftStick;
  70419. if (LSValues && LSValues.y != 0) {
  70420. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70421. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70422. this.camera.inertialRadiusOffset -= normalizedLY;
  70423. }
  70424. }
  70425. }
  70426. };
  70427. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70428. return "ArcRotateCameraGamepadInput";
  70429. };
  70430. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70431. return "gamepad";
  70432. };
  70433. __decorate([
  70434. BABYLON.serialize()
  70435. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70436. __decorate([
  70437. BABYLON.serialize()
  70438. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70439. return ArcRotateCameraGamepadInput;
  70440. }());
  70441. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70442. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70443. })(BABYLON || (BABYLON = {}));
  70444. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70445. var BABYLON;
  70446. (function (BABYLON) {
  70447. var GamepadManager = /** @class */ (function () {
  70448. function GamepadManager(_scene) {
  70449. var _this = this;
  70450. this._scene = _scene;
  70451. this._babylonGamepads = [];
  70452. this._oneGamepadConnected = false;
  70453. this._isMonitoring = false;
  70454. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70455. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70456. this._gamepadEventSupported = false;
  70457. }
  70458. else {
  70459. this._gamepadEventSupported = 'GamepadEvent' in window;
  70460. this._gamepadSupport = (navigator.getGamepads ||
  70461. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70462. }
  70463. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70464. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70465. for (var i in _this._babylonGamepads) {
  70466. var gamepad = _this._babylonGamepads[i];
  70467. if (gamepad && gamepad._isConnected) {
  70468. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70469. }
  70470. }
  70471. });
  70472. this._onGamepadConnectedEvent = function (evt) {
  70473. var gamepad = evt.gamepad;
  70474. if (gamepad.index in _this._babylonGamepads) {
  70475. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70476. return;
  70477. }
  70478. }
  70479. var newGamepad;
  70480. if (_this._babylonGamepads[gamepad.index]) {
  70481. newGamepad = _this._babylonGamepads[gamepad.index];
  70482. newGamepad.browserGamepad = gamepad;
  70483. newGamepad._isConnected = true;
  70484. }
  70485. else {
  70486. newGamepad = _this._addNewGamepad(gamepad);
  70487. }
  70488. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70489. _this._startMonitoringGamepads();
  70490. };
  70491. this._onGamepadDisconnectedEvent = function (evt) {
  70492. var gamepad = evt.gamepad;
  70493. // Remove the gamepad from the list of gamepads to monitor.
  70494. for (var i in _this._babylonGamepads) {
  70495. if (_this._babylonGamepads[i].index === gamepad.index) {
  70496. var disconnectedGamepad = _this._babylonGamepads[i];
  70497. disconnectedGamepad._isConnected = false;
  70498. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70499. break;
  70500. }
  70501. }
  70502. };
  70503. if (this._gamepadSupport) {
  70504. //first add already-connected gamepads
  70505. this._updateGamepadObjects();
  70506. if (this._babylonGamepads.length) {
  70507. this._startMonitoringGamepads();
  70508. }
  70509. // Checking if the gamepad connected event is supported (like in Firefox)
  70510. if (this._gamepadEventSupported) {
  70511. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70512. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70513. }
  70514. else {
  70515. this._startMonitoringGamepads();
  70516. }
  70517. }
  70518. }
  70519. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70520. get: function () {
  70521. return this._babylonGamepads;
  70522. },
  70523. enumerable: true,
  70524. configurable: true
  70525. });
  70526. GamepadManager.prototype.getGamepadByType = function (type) {
  70527. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70528. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70529. var gamepad = _a[_i];
  70530. if (gamepad && gamepad.type === type) {
  70531. return gamepad;
  70532. }
  70533. }
  70534. return null;
  70535. };
  70536. GamepadManager.prototype.dispose = function () {
  70537. if (this._gamepadEventSupported) {
  70538. if (this._onGamepadConnectedEvent) {
  70539. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70540. }
  70541. if (this._onGamepadDisconnectedEvent) {
  70542. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70543. }
  70544. this._onGamepadConnectedEvent = null;
  70545. this._onGamepadDisconnectedEvent = null;
  70546. }
  70547. this._babylonGamepads.forEach(function (gamepad) {
  70548. gamepad.dispose();
  70549. });
  70550. this.onGamepadConnectedObservable.clear();
  70551. this.onGamepadDisconnectedObservable.clear();
  70552. this._oneGamepadConnected = false;
  70553. this._stopMonitoringGamepads();
  70554. this._babylonGamepads = [];
  70555. };
  70556. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70557. if (!this._oneGamepadConnected) {
  70558. this._oneGamepadConnected = true;
  70559. }
  70560. var newGamepad;
  70561. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70562. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70563. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70564. }
  70565. // if pose is supported, use the (WebVR) pose enabled controller
  70566. else if (gamepad.pose) {
  70567. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70568. }
  70569. else {
  70570. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70571. }
  70572. this._babylonGamepads[newGamepad.index] = newGamepad;
  70573. return newGamepad;
  70574. };
  70575. GamepadManager.prototype._startMonitoringGamepads = function () {
  70576. if (!this._isMonitoring) {
  70577. this._isMonitoring = true;
  70578. //back-comp
  70579. if (!this._scene) {
  70580. this._checkGamepadsStatus();
  70581. }
  70582. }
  70583. };
  70584. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70585. this._isMonitoring = false;
  70586. };
  70587. GamepadManager.prototype._checkGamepadsStatus = function () {
  70588. var _this = this;
  70589. // Hack to be compatible Chrome
  70590. this._updateGamepadObjects();
  70591. for (var i in this._babylonGamepads) {
  70592. var gamepad = this._babylonGamepads[i];
  70593. if (!gamepad || !gamepad.isConnected) {
  70594. continue;
  70595. }
  70596. gamepad.update();
  70597. }
  70598. if (this._isMonitoring && !this._scene) {
  70599. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70600. }
  70601. };
  70602. // This function is called only on Chrome, which does not properly support
  70603. // connection/disconnection events and forces you to recopy again the gamepad object
  70604. GamepadManager.prototype._updateGamepadObjects = function () {
  70605. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70606. for (var i = 0; i < gamepads.length; i++) {
  70607. var gamepad = gamepads[i];
  70608. if (gamepad) {
  70609. if (!this._babylonGamepads[gamepad.index]) {
  70610. var newGamepad = this._addNewGamepad(gamepad);
  70611. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70612. }
  70613. else {
  70614. // Forced to copy again this object for Chrome for unknown reason
  70615. this._babylonGamepads[i].browserGamepad = gamepad;
  70616. if (!this._babylonGamepads[i].isConnected) {
  70617. this._babylonGamepads[i]._isConnected = true;
  70618. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70619. }
  70620. }
  70621. }
  70622. }
  70623. };
  70624. return GamepadManager;
  70625. }());
  70626. BABYLON.GamepadManager = GamepadManager;
  70627. })(BABYLON || (BABYLON = {}));
  70628. //# sourceMappingURL=babylon.gamepadManager.js.map
  70629. var BABYLON;
  70630. (function (BABYLON) {
  70631. var StickValues = /** @class */ (function () {
  70632. function StickValues(x, y) {
  70633. this.x = x;
  70634. this.y = y;
  70635. }
  70636. return StickValues;
  70637. }());
  70638. BABYLON.StickValues = StickValues;
  70639. var Gamepad = /** @class */ (function () {
  70640. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70641. if (leftStickX === void 0) { leftStickX = 0; }
  70642. if (leftStickY === void 0) { leftStickY = 1; }
  70643. if (rightStickX === void 0) { rightStickX = 2; }
  70644. if (rightStickY === void 0) { rightStickY = 3; }
  70645. this.id = id;
  70646. this.index = index;
  70647. this.browserGamepad = browserGamepad;
  70648. this._isConnected = true;
  70649. this._invertLeftStickY = false;
  70650. this.type = Gamepad.GAMEPAD;
  70651. this._leftStickAxisX = leftStickX;
  70652. this._leftStickAxisY = leftStickY;
  70653. this._rightStickAxisX = rightStickX;
  70654. this._rightStickAxisY = rightStickY;
  70655. if (this.browserGamepad.axes.length >= 2) {
  70656. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70657. }
  70658. if (this.browserGamepad.axes.length >= 4) {
  70659. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70660. }
  70661. }
  70662. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70663. get: function () {
  70664. return this._isConnected;
  70665. },
  70666. enumerable: true,
  70667. configurable: true
  70668. });
  70669. Gamepad.prototype.onleftstickchanged = function (callback) {
  70670. this._onleftstickchanged = callback;
  70671. };
  70672. Gamepad.prototype.onrightstickchanged = function (callback) {
  70673. this._onrightstickchanged = callback;
  70674. };
  70675. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70676. get: function () {
  70677. return this._leftStick;
  70678. },
  70679. set: function (newValues) {
  70680. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70681. this._onleftstickchanged(newValues);
  70682. }
  70683. this._leftStick = newValues;
  70684. },
  70685. enumerable: true,
  70686. configurable: true
  70687. });
  70688. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70689. get: function () {
  70690. return this._rightStick;
  70691. },
  70692. set: function (newValues) {
  70693. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70694. this._onrightstickchanged(newValues);
  70695. }
  70696. this._rightStick = newValues;
  70697. },
  70698. enumerable: true,
  70699. configurable: true
  70700. });
  70701. Gamepad.prototype.update = function () {
  70702. if (this._leftStick) {
  70703. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70704. if (this._invertLeftStickY) {
  70705. this.leftStick.y *= -1;
  70706. }
  70707. }
  70708. if (this._rightStick) {
  70709. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70710. }
  70711. };
  70712. Gamepad.prototype.dispose = function () {
  70713. };
  70714. Gamepad.GAMEPAD = 0;
  70715. Gamepad.GENERIC = 1;
  70716. Gamepad.XBOX = 2;
  70717. Gamepad.POSE_ENABLED = 3;
  70718. return Gamepad;
  70719. }());
  70720. BABYLON.Gamepad = Gamepad;
  70721. var GenericPad = /** @class */ (function (_super) {
  70722. __extends(GenericPad, _super);
  70723. function GenericPad(id, index, browserGamepad) {
  70724. var _this = _super.call(this, id, index, browserGamepad) || this;
  70725. _this.onButtonDownObservable = new BABYLON.Observable();
  70726. _this.onButtonUpObservable = new BABYLON.Observable();
  70727. _this.type = Gamepad.GENERIC;
  70728. _this._buttons = new Array(browserGamepad.buttons.length);
  70729. return _this;
  70730. }
  70731. GenericPad.prototype.onbuttondown = function (callback) {
  70732. this._onbuttondown = callback;
  70733. };
  70734. GenericPad.prototype.onbuttonup = function (callback) {
  70735. this._onbuttonup = callback;
  70736. };
  70737. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70738. if (newValue !== currentValue) {
  70739. if (newValue === 1) {
  70740. if (this._onbuttondown) {
  70741. this._onbuttondown(buttonIndex);
  70742. }
  70743. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70744. }
  70745. if (newValue === 0) {
  70746. if (this._onbuttonup) {
  70747. this._onbuttonup(buttonIndex);
  70748. }
  70749. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70750. }
  70751. }
  70752. return newValue;
  70753. };
  70754. GenericPad.prototype.update = function () {
  70755. _super.prototype.update.call(this);
  70756. for (var index = 0; index < this._buttons.length; index++) {
  70757. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70758. }
  70759. };
  70760. GenericPad.prototype.dispose = function () {
  70761. _super.prototype.dispose.call(this);
  70762. this.onButtonDownObservable.clear();
  70763. this.onButtonUpObservable.clear();
  70764. };
  70765. return GenericPad;
  70766. }(Gamepad));
  70767. BABYLON.GenericPad = GenericPad;
  70768. })(BABYLON || (BABYLON = {}));
  70769. //# sourceMappingURL=babylon.gamepad.js.map
  70770. var BABYLON;
  70771. (function (BABYLON) {
  70772. /**
  70773. * Defines supported buttons for XBox360 compatible gamepads
  70774. */
  70775. var Xbox360Button;
  70776. (function (Xbox360Button) {
  70777. /** A */
  70778. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70779. /** B */
  70780. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70781. /** X */
  70782. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70783. /** Y */
  70784. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70785. /** Start */
  70786. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70787. /** Back */
  70788. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70789. /** Left button */
  70790. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70791. /** Right button */
  70792. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70793. /** Left stick */
  70794. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70795. /** Right stick */
  70796. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70797. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70798. /** Defines values for XBox360 DPad */
  70799. var Xbox360Dpad;
  70800. (function (Xbox360Dpad) {
  70801. /** Up */
  70802. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70803. /** Down */
  70804. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70805. /** Left */
  70806. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70807. /** Right */
  70808. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70809. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70810. /**
  70811. * Defines a XBox360 gamepad
  70812. */
  70813. var Xbox360Pad = /** @class */ (function (_super) {
  70814. __extends(Xbox360Pad, _super);
  70815. /**
  70816. * Creates a new XBox360 gamepad object
  70817. * @param id defines the id of this gamepad
  70818. * @param index defines its index
  70819. * @param gamepad defines the internal HTML gamepad object
  70820. * @param xboxOne defines if it is a XBox One gamepad
  70821. */
  70822. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70823. if (xboxOne === void 0) { xboxOne = false; }
  70824. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70825. _this._leftTrigger = 0;
  70826. _this._rightTrigger = 0;
  70827. /** Observable raised when a button is pressed */
  70828. _this.onButtonDownObservable = new BABYLON.Observable();
  70829. /** Observable raised when a button is released */
  70830. _this.onButtonUpObservable = new BABYLON.Observable();
  70831. /** Observable raised when a pad is pressed */
  70832. _this.onPadDownObservable = new BABYLON.Observable();
  70833. /** Observable raised when a pad is released */
  70834. _this.onPadUpObservable = new BABYLON.Observable();
  70835. _this._buttonA = 0;
  70836. _this._buttonB = 0;
  70837. _this._buttonX = 0;
  70838. _this._buttonY = 0;
  70839. _this._buttonBack = 0;
  70840. _this._buttonStart = 0;
  70841. _this._buttonLB = 0;
  70842. _this._buttonRB = 0;
  70843. _this._buttonLeftStick = 0;
  70844. _this._buttonRightStick = 0;
  70845. _this._dPadUp = 0;
  70846. _this._dPadDown = 0;
  70847. _this._dPadLeft = 0;
  70848. _this._dPadRight = 0;
  70849. _this._isXboxOnePad = false;
  70850. _this.type = BABYLON.Gamepad.XBOX;
  70851. _this._isXboxOnePad = xboxOne;
  70852. return _this;
  70853. }
  70854. /**
  70855. * Defines the callback to call when left trigger is pressed
  70856. * @param callback defines the callback to use
  70857. */
  70858. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70859. this._onlefttriggerchanged = callback;
  70860. };
  70861. /**
  70862. * Defines the callback to call when right trigger is pressed
  70863. * @param callback defines the callback to use
  70864. */
  70865. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70866. this._onrighttriggerchanged = callback;
  70867. };
  70868. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70869. /**
  70870. * Gets or sets left trigger value
  70871. */
  70872. get: function () {
  70873. return this._leftTrigger;
  70874. },
  70875. set: function (newValue) {
  70876. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70877. this._onlefttriggerchanged(newValue);
  70878. }
  70879. this._leftTrigger = newValue;
  70880. },
  70881. enumerable: true,
  70882. configurable: true
  70883. });
  70884. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70885. /**
  70886. * Gets or sets right trigger value
  70887. */
  70888. get: function () {
  70889. return this._rightTrigger;
  70890. },
  70891. set: function (newValue) {
  70892. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70893. this._onrighttriggerchanged(newValue);
  70894. }
  70895. this._rightTrigger = newValue;
  70896. },
  70897. enumerable: true,
  70898. configurable: true
  70899. });
  70900. /**
  70901. * Defines the callback to call when a button is pressed
  70902. * @param callback defines the callback to use
  70903. */
  70904. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70905. this._onbuttondown = callback;
  70906. };
  70907. /**
  70908. * Defines the callback to call when a button is released
  70909. * @param callback defines the callback to use
  70910. */
  70911. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70912. this._onbuttonup = callback;
  70913. };
  70914. /**
  70915. * Defines the callback to call when a pad is pressed
  70916. * @param callback defines the callback to use
  70917. */
  70918. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70919. this._ondpaddown = callback;
  70920. };
  70921. /**
  70922. * Defines the callback to call when a pad is released
  70923. * @param callback defines the callback to use
  70924. */
  70925. Xbox360Pad.prototype.ondpadup = function (callback) {
  70926. this._ondpadup = callback;
  70927. };
  70928. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70929. if (newValue !== currentValue) {
  70930. if (newValue === 1) {
  70931. if (this._onbuttondown) {
  70932. this._onbuttondown(buttonType);
  70933. }
  70934. this.onButtonDownObservable.notifyObservers(buttonType);
  70935. }
  70936. if (newValue === 0) {
  70937. if (this._onbuttonup) {
  70938. this._onbuttonup(buttonType);
  70939. }
  70940. this.onButtonUpObservable.notifyObservers(buttonType);
  70941. }
  70942. }
  70943. return newValue;
  70944. };
  70945. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70946. if (newValue !== currentValue) {
  70947. if (newValue === 1) {
  70948. if (this._ondpaddown) {
  70949. this._ondpaddown(buttonType);
  70950. }
  70951. this.onPadDownObservable.notifyObservers(buttonType);
  70952. }
  70953. if (newValue === 0) {
  70954. if (this._ondpadup) {
  70955. this._ondpadup(buttonType);
  70956. }
  70957. this.onPadUpObservable.notifyObservers(buttonType);
  70958. }
  70959. }
  70960. return newValue;
  70961. };
  70962. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70963. /** Gets or sets value of A button */
  70964. get: function () {
  70965. return this._buttonA;
  70966. },
  70967. set: function (value) {
  70968. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70969. },
  70970. enumerable: true,
  70971. configurable: true
  70972. });
  70973. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70974. /** Gets or sets value of B button */
  70975. get: function () {
  70976. return this._buttonB;
  70977. },
  70978. set: function (value) {
  70979. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70980. },
  70981. enumerable: true,
  70982. configurable: true
  70983. });
  70984. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70985. /** Gets or sets value of X button */
  70986. get: function () {
  70987. return this._buttonX;
  70988. },
  70989. set: function (value) {
  70990. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70991. },
  70992. enumerable: true,
  70993. configurable: true
  70994. });
  70995. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70996. /** Gets or sets value of Y button */
  70997. get: function () {
  70998. return this._buttonY;
  70999. },
  71000. set: function (value) {
  71001. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71002. },
  71003. enumerable: true,
  71004. configurable: true
  71005. });
  71006. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71007. /** Gets or sets value of Start button */
  71008. get: function () {
  71009. return this._buttonStart;
  71010. },
  71011. set: function (value) {
  71012. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71013. },
  71014. enumerable: true,
  71015. configurable: true
  71016. });
  71017. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71018. /** Gets or sets value of Back button */
  71019. get: function () {
  71020. return this._buttonBack;
  71021. },
  71022. set: function (value) {
  71023. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71024. },
  71025. enumerable: true,
  71026. configurable: true
  71027. });
  71028. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71029. /** Gets or sets value of Left button */
  71030. get: function () {
  71031. return this._buttonLB;
  71032. },
  71033. set: function (value) {
  71034. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71035. },
  71036. enumerable: true,
  71037. configurable: true
  71038. });
  71039. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71040. /** Gets or sets value of Right button */
  71041. get: function () {
  71042. return this._buttonRB;
  71043. },
  71044. set: function (value) {
  71045. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71046. },
  71047. enumerable: true,
  71048. configurable: true
  71049. });
  71050. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71051. /** Gets or sets value of left stick */
  71052. get: function () {
  71053. return this._buttonLeftStick;
  71054. },
  71055. set: function (value) {
  71056. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71057. },
  71058. enumerable: true,
  71059. configurable: true
  71060. });
  71061. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71062. /** Gets or sets value of right stick */
  71063. get: function () {
  71064. return this._buttonRightStick;
  71065. },
  71066. set: function (value) {
  71067. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71068. },
  71069. enumerable: true,
  71070. configurable: true
  71071. });
  71072. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71073. /** Gets or sets value of DPad up */
  71074. get: function () {
  71075. return this._dPadUp;
  71076. },
  71077. set: function (value) {
  71078. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71079. },
  71080. enumerable: true,
  71081. configurable: true
  71082. });
  71083. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71084. /** Gets or sets value of DPad down */
  71085. get: function () {
  71086. return this._dPadDown;
  71087. },
  71088. set: function (value) {
  71089. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71090. },
  71091. enumerable: true,
  71092. configurable: true
  71093. });
  71094. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71095. /** Gets or sets value of DPad left */
  71096. get: function () {
  71097. return this._dPadLeft;
  71098. },
  71099. set: function (value) {
  71100. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71101. },
  71102. enumerable: true,
  71103. configurable: true
  71104. });
  71105. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71106. /** Gets or sets value of DPad right */
  71107. get: function () {
  71108. return this._dPadRight;
  71109. },
  71110. set: function (value) {
  71111. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71112. },
  71113. enumerable: true,
  71114. configurable: true
  71115. });
  71116. /**
  71117. * Force the gamepad to synchronize with device values
  71118. */
  71119. Xbox360Pad.prototype.update = function () {
  71120. _super.prototype.update.call(this);
  71121. if (this._isXboxOnePad) {
  71122. this.buttonA = this.browserGamepad.buttons[0].value;
  71123. this.buttonB = this.browserGamepad.buttons[1].value;
  71124. this.buttonX = this.browserGamepad.buttons[2].value;
  71125. this.buttonY = this.browserGamepad.buttons[3].value;
  71126. this.buttonLB = this.browserGamepad.buttons[4].value;
  71127. this.buttonRB = this.browserGamepad.buttons[5].value;
  71128. this.leftTrigger = this.browserGamepad.axes[2];
  71129. this.rightTrigger = this.browserGamepad.axes[5];
  71130. this.buttonBack = this.browserGamepad.buttons[9].value;
  71131. this.buttonStart = this.browserGamepad.buttons[8].value;
  71132. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71133. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71134. this.dPadUp = this.browserGamepad.buttons[11].value;
  71135. this.dPadDown = this.browserGamepad.buttons[12].value;
  71136. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71137. this.dPadRight = this.browserGamepad.buttons[14].value;
  71138. }
  71139. else {
  71140. this.buttonA = this.browserGamepad.buttons[0].value;
  71141. this.buttonB = this.browserGamepad.buttons[1].value;
  71142. this.buttonX = this.browserGamepad.buttons[2].value;
  71143. this.buttonY = this.browserGamepad.buttons[3].value;
  71144. this.buttonLB = this.browserGamepad.buttons[4].value;
  71145. this.buttonRB = this.browserGamepad.buttons[5].value;
  71146. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71147. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71148. this.buttonBack = this.browserGamepad.buttons[8].value;
  71149. this.buttonStart = this.browserGamepad.buttons[9].value;
  71150. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71151. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71152. this.dPadUp = this.browserGamepad.buttons[12].value;
  71153. this.dPadDown = this.browserGamepad.buttons[13].value;
  71154. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71155. this.dPadRight = this.browserGamepad.buttons[15].value;
  71156. }
  71157. };
  71158. Xbox360Pad.prototype.dispose = function () {
  71159. _super.prototype.dispose.call(this);
  71160. this.onButtonDownObservable.clear();
  71161. this.onButtonUpObservable.clear();
  71162. this.onPadDownObservable.clear();
  71163. this.onPadUpObservable.clear();
  71164. };
  71165. return Xbox360Pad;
  71166. }(BABYLON.Gamepad));
  71167. BABYLON.Xbox360Pad = Xbox360Pad;
  71168. })(BABYLON || (BABYLON = {}));
  71169. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71170. var BABYLON;
  71171. (function (BABYLON) {
  71172. /**
  71173. * Defines the types of pose enabled controllers that are supported
  71174. */
  71175. var PoseEnabledControllerType;
  71176. (function (PoseEnabledControllerType) {
  71177. /**
  71178. * HTC Vive
  71179. */
  71180. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71181. /**
  71182. * Oculus Rift
  71183. */
  71184. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71185. /**
  71186. * Windows mixed reality
  71187. */
  71188. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71189. /**
  71190. * Samsung gear VR
  71191. */
  71192. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71193. /**
  71194. * Google Daydream
  71195. */
  71196. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71197. /**
  71198. * Generic
  71199. */
  71200. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71201. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71202. /**
  71203. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71204. */
  71205. var PoseEnabledControllerHelper = /** @class */ (function () {
  71206. function PoseEnabledControllerHelper() {
  71207. }
  71208. /**
  71209. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71210. * @param vrGamepad the gamepad to initialized
  71211. * @returns a vr controller of the type the gamepad identified as
  71212. */
  71213. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71214. // Oculus Touch
  71215. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71216. return new BABYLON.OculusTouchController(vrGamepad);
  71217. }
  71218. // Windows Mixed Reality controllers
  71219. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71220. return new BABYLON.WindowsMotionController(vrGamepad);
  71221. }
  71222. // HTC Vive
  71223. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71224. return new BABYLON.ViveController(vrGamepad);
  71225. }
  71226. // Samsung/Oculus Gear VR or Oculus Go
  71227. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71228. return new BABYLON.GearVRController(vrGamepad);
  71229. }
  71230. // Google Daydream
  71231. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71232. return new BABYLON.DaydreamController(vrGamepad);
  71233. }
  71234. // Generic
  71235. else {
  71236. return new BABYLON.GenericController(vrGamepad);
  71237. }
  71238. };
  71239. return PoseEnabledControllerHelper;
  71240. }());
  71241. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71242. /**
  71243. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71244. */
  71245. var PoseEnabledController = /** @class */ (function (_super) {
  71246. __extends(PoseEnabledController, _super);
  71247. /**
  71248. * Creates a new PoseEnabledController from a gamepad
  71249. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71250. */
  71251. function PoseEnabledController(browserGamepad) {
  71252. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71253. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71254. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71255. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71256. /**
  71257. * The device position in babylon space
  71258. */
  71259. _this.devicePosition = BABYLON.Vector3.Zero();
  71260. /**
  71261. * The device rotation in babylon space
  71262. */
  71263. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71264. /**
  71265. * The scale factor of the device in babylon space
  71266. */
  71267. _this.deviceScaleFactor = 1;
  71268. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71269. /**
  71270. * Internal, matrix used to convert room space to babylon space
  71271. */
  71272. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71273. /**
  71274. * Node to be used when casting a ray from the controller
  71275. */
  71276. _this._pointingPoseNode = null;
  71277. _this._workingMatrix = BABYLON.Matrix.Identity();
  71278. /**
  71279. * @hidden
  71280. */
  71281. _this._meshAttachedObservable = new BABYLON.Observable();
  71282. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71283. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71284. _this.position = BABYLON.Vector3.Zero();
  71285. _this.rotationQuaternion = new BABYLON.Quaternion();
  71286. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71287. _this._calculatedRotation = new BABYLON.Quaternion();
  71288. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71289. return _this;
  71290. }
  71291. /**
  71292. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71293. */
  71294. PoseEnabledController.prototype.update = function () {
  71295. _super.prototype.update.call(this);
  71296. var pose = this.browserGamepad.pose;
  71297. this.updateFromDevice(pose);
  71298. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71299. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71300. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71301. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71302. if (this._mesh) {
  71303. this._mesh.position.copyFrom(this.devicePosition);
  71304. if (this._mesh.rotationQuaternion) {
  71305. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71306. }
  71307. }
  71308. };
  71309. /**
  71310. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71311. * @param poseData raw pose fromthe device
  71312. */
  71313. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71314. if (poseData) {
  71315. this.rawPose = poseData;
  71316. if (poseData.position) {
  71317. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71318. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71319. this._deviceRoomPosition.z *= -1;
  71320. }
  71321. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71322. this._calculatedPosition.addInPlace(this.position);
  71323. }
  71324. var pose = this.rawPose;
  71325. if (poseData.orientation && pose.orientation) {
  71326. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71327. if (this._mesh) {
  71328. if (this._mesh.getScene().useRightHandedSystem) {
  71329. this._deviceRoomRotationQuaternion.z *= -1;
  71330. this._deviceRoomRotationQuaternion.w *= -1;
  71331. }
  71332. else {
  71333. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71334. }
  71335. }
  71336. // if the camera is set, rotate to the camera's rotation
  71337. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71338. }
  71339. }
  71340. };
  71341. /**
  71342. * Attaches a mesh to the controller
  71343. * @param mesh the mesh to be attached
  71344. */
  71345. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71346. if (this._mesh) {
  71347. this._mesh.parent = null;
  71348. }
  71349. this._mesh = mesh;
  71350. if (this._poseControlledCamera) {
  71351. this._mesh.parent = this._poseControlledCamera;
  71352. }
  71353. if (!this._mesh.rotationQuaternion) {
  71354. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71355. }
  71356. // Sync controller mesh and pointing pose node's state with controller
  71357. this.update();
  71358. if (this._pointingPoseNode) {
  71359. var parents = [];
  71360. var obj = this._pointingPoseNode;
  71361. while (obj.parent) {
  71362. parents.push(obj.parent);
  71363. obj = obj.parent;
  71364. }
  71365. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  71366. }
  71367. this._meshAttachedObservable.notifyObservers(mesh);
  71368. };
  71369. /**
  71370. * Attaches the controllers mesh to a camera
  71371. * @param camera the camera the mesh should be attached to
  71372. */
  71373. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71374. this._poseControlledCamera = camera;
  71375. if (this._mesh) {
  71376. this._mesh.parent = this._poseControlledCamera;
  71377. }
  71378. };
  71379. /**
  71380. * Disposes of the controller
  71381. */
  71382. PoseEnabledController.prototype.dispose = function () {
  71383. if (this._mesh) {
  71384. this._mesh.dispose();
  71385. }
  71386. this._mesh = null;
  71387. _super.prototype.dispose.call(this);
  71388. };
  71389. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71390. /**
  71391. * The mesh that is attached to the controller
  71392. */
  71393. get: function () {
  71394. return this._mesh;
  71395. },
  71396. enumerable: true,
  71397. configurable: true
  71398. });
  71399. /**
  71400. * Gets the ray of the controller in the direction the controller is pointing
  71401. * @param length the length the resulting ray should be
  71402. * @returns a ray in the direction the controller is pointing
  71403. */
  71404. PoseEnabledController.prototype.getForwardRay = function (length) {
  71405. if (length === void 0) { length = 100; }
  71406. if (!this.mesh) {
  71407. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71408. }
  71409. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71410. var origin = m.getTranslation();
  71411. var forward = new BABYLON.Vector3(0, 0, -1);
  71412. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71413. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71414. return new BABYLON.Ray(origin, direction, length);
  71415. };
  71416. /**
  71417. * Name of the child mesh that can be used to cast a ray from the controller
  71418. */
  71419. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71420. return PoseEnabledController;
  71421. }(BABYLON.Gamepad));
  71422. BABYLON.PoseEnabledController = PoseEnabledController;
  71423. })(BABYLON || (BABYLON = {}));
  71424. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71425. var BABYLON;
  71426. (function (BABYLON) {
  71427. /**
  71428. * Defines the WebVRController object that represents controllers tracked in 3D space
  71429. */
  71430. var WebVRController = /** @class */ (function (_super) {
  71431. __extends(WebVRController, _super);
  71432. /**
  71433. * Creates a new WebVRController from a gamepad
  71434. * @param vrGamepad the gamepad that the WebVRController should be created from
  71435. */
  71436. function WebVRController(vrGamepad) {
  71437. var _this = _super.call(this, vrGamepad) || this;
  71438. // Observables
  71439. /**
  71440. * Fired when the trigger state has changed
  71441. */
  71442. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71443. /**
  71444. * Fired when the main button state has changed
  71445. */
  71446. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71447. /**
  71448. * Fired when the secondary button state has changed
  71449. */
  71450. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71451. /**
  71452. * Fired when the pad state has changed
  71453. */
  71454. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71455. /**
  71456. * Fired when controllers stick values have changed
  71457. */
  71458. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71459. /**
  71460. * X and Y axis corrisponding to the controllers joystick
  71461. */
  71462. _this.pad = { x: 0, y: 0 };
  71463. // avoid GC, store state in a tmp object
  71464. _this._changes = {
  71465. pressChanged: false,
  71466. touchChanged: false,
  71467. valueChanged: false,
  71468. changed: false
  71469. };
  71470. _this._buttons = new Array(vrGamepad.buttons.length);
  71471. _this.hand = vrGamepad.hand;
  71472. return _this;
  71473. }
  71474. /**
  71475. * Fired when a controller button's state has changed
  71476. * @param callback the callback containing the button that was modified
  71477. */
  71478. WebVRController.prototype.onButtonStateChange = function (callback) {
  71479. this._onButtonStateChange = callback;
  71480. };
  71481. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71482. /**
  71483. * The default controller model for the controller
  71484. */
  71485. get: function () {
  71486. return this._defaultModel;
  71487. },
  71488. enumerable: true,
  71489. configurable: true
  71490. });
  71491. /**
  71492. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71493. */
  71494. WebVRController.prototype.update = function () {
  71495. _super.prototype.update.call(this);
  71496. for (var index = 0; index < this._buttons.length; index++) {
  71497. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71498. }
  71499. ;
  71500. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71501. this.pad.x = this.leftStick.x;
  71502. this.pad.y = this.leftStick.y;
  71503. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71504. }
  71505. };
  71506. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71507. if (!newState) {
  71508. newState = {
  71509. pressed: false,
  71510. touched: false,
  71511. value: 0
  71512. };
  71513. }
  71514. if (!currentState) {
  71515. this._buttons[buttonIndex] = {
  71516. pressed: newState.pressed,
  71517. touched: newState.touched,
  71518. value: newState.value
  71519. };
  71520. return;
  71521. }
  71522. this._checkChanges(newState, currentState);
  71523. if (this._changes.changed) {
  71524. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71525. this._handleButtonChange(buttonIndex, newState, this._changes);
  71526. }
  71527. this._buttons[buttonIndex].pressed = newState.pressed;
  71528. this._buttons[buttonIndex].touched = newState.touched;
  71529. // oculus triggers are never 0, thou not touched.
  71530. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71531. };
  71532. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71533. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71534. this._changes.touchChanged = newState.touched !== currentState.touched;
  71535. this._changes.valueChanged = newState.value !== currentState.value;
  71536. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71537. return this._changes;
  71538. };
  71539. /**
  71540. * Disposes of th webVRCOntroller
  71541. */
  71542. WebVRController.prototype.dispose = function () {
  71543. _super.prototype.dispose.call(this);
  71544. this.onTriggerStateChangedObservable.clear();
  71545. this.onMainButtonStateChangedObservable.clear();
  71546. this.onSecondaryButtonStateChangedObservable.clear();
  71547. this.onPadStateChangedObservable.clear();
  71548. this.onPadValuesChangedObservable.clear();
  71549. };
  71550. return WebVRController;
  71551. }(BABYLON.PoseEnabledController));
  71552. BABYLON.WebVRController = WebVRController;
  71553. })(BABYLON || (BABYLON = {}));
  71554. //# sourceMappingURL=babylon.webVRController.js.map
  71555. var BABYLON;
  71556. (function (BABYLON) {
  71557. /**
  71558. * Oculus Touch Controller
  71559. */
  71560. var OculusTouchController = /** @class */ (function (_super) {
  71561. __extends(OculusTouchController, _super);
  71562. /**
  71563. * Creates a new OculusTouchController from a gamepad
  71564. * @param vrGamepad the gamepad that the controller should be created from
  71565. */
  71566. function OculusTouchController(vrGamepad) {
  71567. var _this = _super.call(this, vrGamepad) || this;
  71568. /**
  71569. * Fired when the secondary trigger on this controller is modified
  71570. */
  71571. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71572. /**
  71573. * Fired when the thumb rest on this controller is modified
  71574. */
  71575. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71576. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71577. return _this;
  71578. }
  71579. /**
  71580. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71581. * @param scene scene in which to add meshes
  71582. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71583. */
  71584. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71585. var _this = this;
  71586. var meshName;
  71587. // Hand
  71588. if (this.hand === 'left') {
  71589. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71590. }
  71591. else { // Right is the default if no hand is specified
  71592. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71593. }
  71594. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71595. /*
  71596. Parent Mesh name: oculus_touch_left
  71597. - body
  71598. - trigger
  71599. - thumbstick
  71600. - grip
  71601. - button_y
  71602. - button_x
  71603. - button_enter
  71604. */
  71605. _this._defaultModel = newMeshes[1];
  71606. _this.attachToMesh(_this._defaultModel);
  71607. if (meshLoaded) {
  71608. meshLoaded(_this._defaultModel);
  71609. }
  71610. });
  71611. };
  71612. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71613. /**
  71614. * Fired when the A button on this controller is modified
  71615. */
  71616. get: function () {
  71617. if (this.hand === 'right') {
  71618. return this.onMainButtonStateChangedObservable;
  71619. }
  71620. else {
  71621. throw new Error('No A button on left hand');
  71622. }
  71623. },
  71624. enumerable: true,
  71625. configurable: true
  71626. });
  71627. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71628. /**
  71629. * Fired when the B button on this controller is modified
  71630. */
  71631. get: function () {
  71632. if (this.hand === 'right') {
  71633. return this.onSecondaryButtonStateChangedObservable;
  71634. }
  71635. else {
  71636. throw new Error('No B button on left hand');
  71637. }
  71638. },
  71639. enumerable: true,
  71640. configurable: true
  71641. });
  71642. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71643. /**
  71644. * Fired when the X button on this controller is modified
  71645. */
  71646. get: function () {
  71647. if (this.hand === 'left') {
  71648. return this.onMainButtonStateChangedObservable;
  71649. }
  71650. else {
  71651. throw new Error('No X button on right hand');
  71652. }
  71653. },
  71654. enumerable: true,
  71655. configurable: true
  71656. });
  71657. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71658. /**
  71659. * Fired when the Y button on this controller is modified
  71660. */
  71661. get: function () {
  71662. if (this.hand === 'left') {
  71663. return this.onSecondaryButtonStateChangedObservable;
  71664. }
  71665. else {
  71666. throw new Error('No Y button on right hand');
  71667. }
  71668. },
  71669. enumerable: true,
  71670. configurable: true
  71671. });
  71672. /**
  71673. * Called once for each button that changed state since the last frame
  71674. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71675. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71676. * 2) secondary trigger (same)
  71677. * 3) A (right) X (left), touch, pressed = value
  71678. * 4) B / Y
  71679. * 5) thumb rest
  71680. * @param buttonIdx Which button index changed
  71681. * @param state New state of the button
  71682. * @param changes Which properties on the state changed since last frame
  71683. */
  71684. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71685. var notifyObject = state; //{ state: state, changes: changes };
  71686. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71687. switch (buttonIdx) {
  71688. case 0:
  71689. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71690. return;
  71691. case 1: // index trigger
  71692. if (this._defaultModel) {
  71693. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71694. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71695. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71696. }
  71697. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71698. return;
  71699. case 2: // secondary trigger
  71700. if (this._defaultModel) {
  71701. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71702. }
  71703. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71704. return;
  71705. case 3:
  71706. if (this._defaultModel) {
  71707. if (notifyObject.pressed) {
  71708. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71709. }
  71710. else {
  71711. (this._defaultModel.getChildren()[1]).position.y = 0;
  71712. }
  71713. }
  71714. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71715. return;
  71716. case 4:
  71717. if (this._defaultModel) {
  71718. if (notifyObject.pressed) {
  71719. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71720. }
  71721. else {
  71722. (this._defaultModel.getChildren()[2]).position.y = 0;
  71723. }
  71724. }
  71725. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71726. return;
  71727. case 5:
  71728. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71729. return;
  71730. }
  71731. };
  71732. /**
  71733. * Base Url for the controller model.
  71734. */
  71735. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71736. /**
  71737. * File name for the left controller model.
  71738. */
  71739. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71740. /**
  71741. * File name for the right controller model.
  71742. */
  71743. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71744. return OculusTouchController;
  71745. }(BABYLON.WebVRController));
  71746. BABYLON.OculusTouchController = OculusTouchController;
  71747. })(BABYLON || (BABYLON = {}));
  71748. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71749. var BABYLON;
  71750. (function (BABYLON) {
  71751. /**
  71752. * Vive Controller
  71753. */
  71754. var ViveController = /** @class */ (function (_super) {
  71755. __extends(ViveController, _super);
  71756. /**
  71757. * Creates a new ViveController from a gamepad
  71758. * @param vrGamepad the gamepad that the controller should be created from
  71759. */
  71760. function ViveController(vrGamepad) {
  71761. var _this = _super.call(this, vrGamepad) || this;
  71762. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71763. _this._invertLeftStickY = true;
  71764. return _this;
  71765. }
  71766. /**
  71767. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71768. * @param scene scene in which to add meshes
  71769. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71770. */
  71771. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71772. var _this = this;
  71773. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71774. /*
  71775. Parent Mesh name: ViveWand
  71776. - body
  71777. - r_gripper
  71778. - l_gripper
  71779. - menu_button
  71780. - system_button
  71781. - trackpad
  71782. - trigger
  71783. - LED
  71784. */
  71785. _this._defaultModel = newMeshes[1];
  71786. _this.attachToMesh(_this._defaultModel);
  71787. if (meshLoaded) {
  71788. meshLoaded(_this._defaultModel);
  71789. }
  71790. });
  71791. };
  71792. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71793. /**
  71794. * Fired when the left button on this controller is modified
  71795. */
  71796. get: function () {
  71797. return this.onMainButtonStateChangedObservable;
  71798. },
  71799. enumerable: true,
  71800. configurable: true
  71801. });
  71802. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71803. /**
  71804. * Fired when the right button on this controller is modified
  71805. */
  71806. get: function () {
  71807. return this.onMainButtonStateChangedObservable;
  71808. },
  71809. enumerable: true,
  71810. configurable: true
  71811. });
  71812. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71813. /**
  71814. * Fired when the menu button on this controller is modified
  71815. */
  71816. get: function () {
  71817. return this.onSecondaryButtonStateChangedObservable;
  71818. },
  71819. enumerable: true,
  71820. configurable: true
  71821. });
  71822. /**
  71823. * Called once for each button that changed state since the last frame
  71824. * Vive mapping:
  71825. * 0: touchpad
  71826. * 1: trigger
  71827. * 2: left AND right buttons
  71828. * 3: menu button
  71829. * @param buttonIdx Which button index changed
  71830. * @param state New state of the button
  71831. * @param changes Which properties on the state changed since last frame
  71832. */
  71833. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71834. var notifyObject = state; //{ state: state, changes: changes };
  71835. switch (buttonIdx) {
  71836. case 0:
  71837. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71838. return;
  71839. case 1: // index trigger
  71840. if (this._defaultModel) {
  71841. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71842. }
  71843. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71844. return;
  71845. case 2: // left AND right button
  71846. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71847. return;
  71848. case 3:
  71849. if (this._defaultModel) {
  71850. if (notifyObject.pressed) {
  71851. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71852. }
  71853. else {
  71854. (this._defaultModel.getChildren()[2]).position.y = 0;
  71855. }
  71856. }
  71857. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71858. return;
  71859. }
  71860. };
  71861. /**
  71862. * Base Url for the controller model.
  71863. */
  71864. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71865. /**
  71866. * File name for the controller model.
  71867. */
  71868. ViveController.MODEL_FILENAME = 'wand.babylon';
  71869. return ViveController;
  71870. }(BABYLON.WebVRController));
  71871. BABYLON.ViveController = ViveController;
  71872. })(BABYLON || (BABYLON = {}));
  71873. //# sourceMappingURL=babylon.viveController.js.map
  71874. var BABYLON;
  71875. (function (BABYLON) {
  71876. /**
  71877. * Generic Controller
  71878. */
  71879. var GenericController = /** @class */ (function (_super) {
  71880. __extends(GenericController, _super);
  71881. /**
  71882. * Creates a new GenericController from a gamepad
  71883. * @param vrGamepad the gamepad that the controller should be created from
  71884. */
  71885. function GenericController(vrGamepad) {
  71886. return _super.call(this, vrGamepad) || this;
  71887. }
  71888. /**
  71889. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71890. * @param scene scene in which to add meshes
  71891. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71892. */
  71893. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71894. var _this = this;
  71895. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71896. _this._defaultModel = newMeshes[1];
  71897. _this.attachToMesh(_this._defaultModel);
  71898. if (meshLoaded) {
  71899. meshLoaded(_this._defaultModel);
  71900. }
  71901. });
  71902. };
  71903. /**
  71904. * Called once for each button that changed state since the last frame
  71905. * @param buttonIdx Which button index changed
  71906. * @param state New state of the button
  71907. * @param changes Which properties on the state changed since last frame
  71908. */
  71909. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71910. console.log("Button id: " + buttonIdx + "state: ");
  71911. console.dir(state);
  71912. };
  71913. /**
  71914. * Base Url for the controller model.
  71915. */
  71916. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71917. /**
  71918. * File name for the controller model.
  71919. */
  71920. GenericController.MODEL_FILENAME = 'generic.babylon';
  71921. return GenericController;
  71922. }(BABYLON.WebVRController));
  71923. BABYLON.GenericController = GenericController;
  71924. })(BABYLON || (BABYLON = {}));
  71925. //# sourceMappingURL=babylon.genericController.js.map
  71926. var BABYLON;
  71927. (function (BABYLON) {
  71928. /**
  71929. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71930. */
  71931. var LoadedMeshInfo = /** @class */ (function () {
  71932. function LoadedMeshInfo() {
  71933. /**
  71934. * Map of the button meshes contained in the controller
  71935. */
  71936. this.buttonMeshes = {};
  71937. /**
  71938. * Map of the axis meshes contained in the controller
  71939. */
  71940. this.axisMeshes = {};
  71941. }
  71942. return LoadedMeshInfo;
  71943. }());
  71944. /**
  71945. * Defines the WindowsMotionController object that the state of the windows motion controller
  71946. */
  71947. var WindowsMotionController = /** @class */ (function (_super) {
  71948. __extends(WindowsMotionController, _super);
  71949. /**
  71950. * Creates a new WindowsMotionController from a gamepad
  71951. * @param vrGamepad the gamepad that the controller should be created from
  71952. */
  71953. function WindowsMotionController(vrGamepad) {
  71954. var _this = _super.call(this, vrGamepad) || this;
  71955. _this._mapping = {
  71956. // Semantic button names
  71957. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71958. // A mapping of the button name to glTF model node name
  71959. // that should be transformed by button value.
  71960. buttonMeshNames: {
  71961. 'trigger': 'SELECT',
  71962. 'menu': 'MENU',
  71963. 'grip': 'GRASP',
  71964. 'thumbstick': 'THUMBSTICK_PRESS',
  71965. 'trackpad': 'TOUCHPAD_PRESS'
  71966. },
  71967. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71968. buttonObservableNames: {
  71969. 'trigger': 'onTriggerStateChangedObservable',
  71970. 'menu': 'onSecondaryButtonStateChangedObservable',
  71971. 'grip': 'onMainButtonStateChangedObservable',
  71972. 'thumbstick': 'onPadStateChangedObservable',
  71973. 'trackpad': 'onTrackpadChangedObservable'
  71974. },
  71975. // A mapping of the axis name to glTF model node name
  71976. // that should be transformed by axis value.
  71977. // This array mirrors the browserGamepad.axes array, such that
  71978. // the mesh corresponding to axis 0 is in this array index 0.
  71979. axisMeshNames: [
  71980. 'THUMBSTICK_X',
  71981. 'THUMBSTICK_Y',
  71982. 'TOUCHPAD_TOUCH_X',
  71983. 'TOUCHPAD_TOUCH_Y'
  71984. ],
  71985. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71986. };
  71987. /**
  71988. * Fired when the trackpad on this controller is clicked
  71989. */
  71990. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71991. /**
  71992. * Fired when the trackpad on this controller is modified
  71993. */
  71994. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71995. /**
  71996. * The current x and y values of this controller's trackpad
  71997. */
  71998. _this.trackpad = { x: 0, y: 0 };
  71999. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72000. _this._loadedMeshInfo = null;
  72001. return _this;
  72002. }
  72003. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72004. /**
  72005. * Fired when the trigger on this controller is modified
  72006. */
  72007. get: function () {
  72008. return this.onTriggerStateChangedObservable;
  72009. },
  72010. enumerable: true,
  72011. configurable: true
  72012. });
  72013. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72014. /**
  72015. * Fired when the menu button on this controller is modified
  72016. */
  72017. get: function () {
  72018. return this.onSecondaryButtonStateChangedObservable;
  72019. },
  72020. enumerable: true,
  72021. configurable: true
  72022. });
  72023. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72024. /**
  72025. * Fired when the grip button on this controller is modified
  72026. */
  72027. get: function () {
  72028. return this.onMainButtonStateChangedObservable;
  72029. },
  72030. enumerable: true,
  72031. configurable: true
  72032. });
  72033. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72034. /**
  72035. * Fired when the thumbstick button on this controller is modified
  72036. */
  72037. get: function () {
  72038. return this.onPadStateChangedObservable;
  72039. },
  72040. enumerable: true,
  72041. configurable: true
  72042. });
  72043. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72044. /**
  72045. * Fired when the touchpad button on this controller is modified
  72046. */
  72047. get: function () {
  72048. return this.onTrackpadChangedObservable;
  72049. },
  72050. enumerable: true,
  72051. configurable: true
  72052. });
  72053. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72054. /**
  72055. * Fired when the touchpad values on this controller are modified
  72056. */
  72057. get: function () {
  72058. return this.onTrackpadValuesChangedObservable;
  72059. },
  72060. enumerable: true,
  72061. configurable: true
  72062. });
  72063. WindowsMotionController.prototype._updateTrackpad = function () {
  72064. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  72065. this.trackpad.x = this.browserGamepad["axes"][2];
  72066. this.trackpad.y = this.browserGamepad["axes"][3];
  72067. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72068. }
  72069. };
  72070. /**
  72071. * Called once per frame by the engine.
  72072. */
  72073. WindowsMotionController.prototype.update = function () {
  72074. _super.prototype.update.call(this);
  72075. if (this.browserGamepad.axes) {
  72076. this._updateTrackpad();
  72077. // Only need to animate axes if there is a loaded mesh
  72078. if (this._loadedMeshInfo) {
  72079. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72080. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72081. }
  72082. }
  72083. }
  72084. };
  72085. /**
  72086. * Called once for each button that changed state since the last frame
  72087. * @param buttonIdx Which button index changed
  72088. * @param state New state of the button
  72089. * @param changes Which properties on the state changed since last frame
  72090. */
  72091. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72092. var buttonName = this._mapping.buttons[buttonIdx];
  72093. if (!buttonName) {
  72094. return;
  72095. }
  72096. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  72097. this._updateTrackpad();
  72098. // Only emit events for buttons that we know how to map from index to name
  72099. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72100. if (observable) {
  72101. observable.notifyObservers(state);
  72102. }
  72103. this._lerpButtonTransform(buttonName, state.value);
  72104. };
  72105. /**
  72106. * Moves the buttons on the controller mesh based on their current state
  72107. * @param buttonName the name of the button to move
  72108. * @param buttonValue the value of the button which determines the buttons new position
  72109. */
  72110. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72111. // If there is no loaded mesh, there is nothing to transform.
  72112. if (!this._loadedMeshInfo) {
  72113. return;
  72114. }
  72115. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72116. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72117. return;
  72118. }
  72119. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72120. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72121. };
  72122. /**
  72123. * Moves the axis on the controller mesh based on its current state
  72124. * @param axis the index of the axis
  72125. * @param axisValue the value of the axis which determines the meshes new position
  72126. * @hidden
  72127. */
  72128. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72129. if (!this._loadedMeshInfo) {
  72130. return;
  72131. }
  72132. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72133. if (!meshInfo) {
  72134. return;
  72135. }
  72136. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72137. return;
  72138. }
  72139. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72140. var lerpValue = axisValue * 0.5 + 0.5;
  72141. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72142. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72143. };
  72144. /**
  72145. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72146. * @param scene scene in which to add meshes
  72147. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72148. */
  72149. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72150. var _this = this;
  72151. if (forceDefault === void 0) { forceDefault = false; }
  72152. var path;
  72153. var filename;
  72154. // Checking if GLB loader is present
  72155. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72156. // Determine the device specific folder based on the ID suffix
  72157. var device = 'default';
  72158. if (this.id && !forceDefault) {
  72159. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72160. device = ((match && match[0]) || device);
  72161. }
  72162. // Hand
  72163. if (this.hand === 'left') {
  72164. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72165. }
  72166. else { // Right is the default if no hand is specified
  72167. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72168. }
  72169. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72170. }
  72171. else {
  72172. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72173. path = BABYLON.GenericController.MODEL_BASE_URL;
  72174. filename = BABYLON.GenericController.MODEL_FILENAME;
  72175. }
  72176. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72177. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72178. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72179. if (!_this._loadedMeshInfo) {
  72180. return;
  72181. }
  72182. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72183. _this.attachToMesh(_this._defaultModel);
  72184. if (meshLoaded) {
  72185. meshLoaded(_this._defaultModel);
  72186. }
  72187. }, null, function (scene, message) {
  72188. BABYLON.Tools.Log(message);
  72189. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72190. if (!forceDefault) {
  72191. _this.initControllerMesh(scene, meshLoaded, true);
  72192. }
  72193. });
  72194. };
  72195. /**
  72196. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72197. * can be transformed by button presses and axes values, based on this._mapping.
  72198. *
  72199. * @param scene scene in which the meshes exist
  72200. * @param meshes list of meshes that make up the controller model to process
  72201. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72202. */
  72203. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72204. var loadedMeshInfo = null;
  72205. // Create a new mesh to contain the glTF hierarchy
  72206. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72207. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72208. var childMesh = null;
  72209. for (var i = 0; i < meshes.length; i++) {
  72210. var mesh = meshes[i];
  72211. if (!mesh.parent) {
  72212. // Exclude controller meshes from picking results
  72213. mesh.isPickable = false;
  72214. // Handle root node, attach to the new parentMesh
  72215. childMesh = mesh;
  72216. break;
  72217. }
  72218. }
  72219. if (childMesh) {
  72220. childMesh.setParent(parentMesh);
  72221. // Create our mesh info. Note that this method will always return non-null.
  72222. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72223. }
  72224. else {
  72225. BABYLON.Tools.Warn('Could not find root node in model file.');
  72226. }
  72227. return loadedMeshInfo;
  72228. };
  72229. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72230. var loadedMeshInfo = new LoadedMeshInfo();
  72231. var i;
  72232. loadedMeshInfo.rootNode = rootNode;
  72233. // Reset the caches
  72234. loadedMeshInfo.buttonMeshes = {};
  72235. loadedMeshInfo.axisMeshes = {};
  72236. // Button Meshes
  72237. for (i = 0; i < this._mapping.buttons.length; i++) {
  72238. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72239. if (!buttonMeshName) {
  72240. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72241. continue;
  72242. }
  72243. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72244. if (!buttonMesh) {
  72245. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72246. continue;
  72247. }
  72248. var buttonMeshInfo = {
  72249. index: i,
  72250. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72251. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72252. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72253. };
  72254. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72255. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72256. }
  72257. else {
  72258. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72259. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72260. '(VALUE: ' + !!buttonMeshInfo.value +
  72261. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72262. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72263. ')');
  72264. }
  72265. }
  72266. // Axis Meshes
  72267. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72268. var axisMeshName = this._mapping.axisMeshNames[i];
  72269. if (!axisMeshName) {
  72270. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72271. continue;
  72272. }
  72273. var axisMesh = getChildByName(rootNode, axisMeshName);
  72274. if (!axisMesh) {
  72275. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72276. continue;
  72277. }
  72278. var axisMeshInfo = {
  72279. index: i,
  72280. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72281. min: getImmediateChildByName(axisMesh, 'MIN'),
  72282. max: getImmediateChildByName(axisMesh, 'MAX')
  72283. };
  72284. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72285. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72286. }
  72287. else {
  72288. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72289. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72290. '(VALUE: ' + !!axisMeshInfo.value +
  72291. ', MIN: ' + !!axisMeshInfo.min +
  72292. ', MAX:' + !!axisMeshInfo.max +
  72293. ')');
  72294. }
  72295. }
  72296. // Pointing Ray
  72297. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72298. if (!loadedMeshInfo.pointingPoseNode) {
  72299. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72300. }
  72301. else {
  72302. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  72303. }
  72304. return loadedMeshInfo;
  72305. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72306. function getChildByName(node, name) {
  72307. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72308. }
  72309. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72310. function getImmediateChildByName(node, name) {
  72311. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72312. }
  72313. };
  72314. /**
  72315. * Gets the ray of the controller in the direction the controller is pointing
  72316. * @param length the length the resulting ray should be
  72317. * @returns a ray in the direction the controller is pointing
  72318. */
  72319. WindowsMotionController.prototype.getForwardRay = function (length) {
  72320. if (length === void 0) { length = 100; }
  72321. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72322. return _super.prototype.getForwardRay.call(this, length);
  72323. }
  72324. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72325. var origin = m.getTranslation();
  72326. var forward = new BABYLON.Vector3(0, 0, -1);
  72327. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72328. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72329. return new BABYLON.Ray(origin, direction, length);
  72330. };
  72331. /**
  72332. * Disposes of the controller
  72333. */
  72334. WindowsMotionController.prototype.dispose = function () {
  72335. _super.prototype.dispose.call(this);
  72336. this.onTrackpadChangedObservable.clear();
  72337. };
  72338. /**
  72339. * The base url used to load the left and right controller models
  72340. */
  72341. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72342. /**
  72343. * The name of the left controller model file
  72344. */
  72345. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72346. /**
  72347. * The name of the right controller model file
  72348. */
  72349. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72350. /**
  72351. * The controller name prefix for this controller type
  72352. */
  72353. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72354. /**
  72355. * The controller id pattern for this controller type
  72356. */
  72357. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72358. return WindowsMotionController;
  72359. }(BABYLON.WebVRController));
  72360. BABYLON.WindowsMotionController = WindowsMotionController;
  72361. })(BABYLON || (BABYLON = {}));
  72362. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72363. var BABYLON;
  72364. (function (BABYLON) {
  72365. /**
  72366. * Gear VR Controller
  72367. */
  72368. var GearVRController = /** @class */ (function (_super) {
  72369. __extends(GearVRController, _super);
  72370. /**
  72371. * Creates a new GearVRController from a gamepad
  72372. * @param vrGamepad the gamepad that the controller should be created from
  72373. */
  72374. function GearVRController(vrGamepad) {
  72375. var _this = _super.call(this, vrGamepad) || this;
  72376. _this._buttonIndexToObservableNameMap = [
  72377. 'onTrackpadChangedObservable',
  72378. 'onTriggerStateChangedObservable' // Trigger
  72379. ];
  72380. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72381. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72382. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72383. return _this;
  72384. }
  72385. /**
  72386. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72387. * @param scene scene in which to add meshes
  72388. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72389. */
  72390. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72391. var _this = this;
  72392. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72393. _this._defaultModel = newMeshes[1];
  72394. _this.attachToMesh(_this._defaultModel);
  72395. if (meshLoaded) {
  72396. meshLoaded(_this._defaultModel);
  72397. }
  72398. });
  72399. };
  72400. /**
  72401. * Called once for each button that changed state since the last frame
  72402. * @param buttonIdx Which button index changed
  72403. * @param state New state of the button
  72404. * @param changes Which properties on the state changed since last frame
  72405. */
  72406. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72407. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72408. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72409. // Only emit events for buttons that we know how to map from index to observable
  72410. var observable = this[observableName];
  72411. if (observable) {
  72412. observable.notifyObservers(state);
  72413. }
  72414. }
  72415. };
  72416. /**
  72417. * Base Url for the controller model.
  72418. */
  72419. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72420. /**
  72421. * File name for the controller model.
  72422. */
  72423. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72424. /**
  72425. * Gamepad Id prefix used to identify this controller.
  72426. */
  72427. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72428. return GearVRController;
  72429. }(BABYLON.WebVRController));
  72430. BABYLON.GearVRController = GearVRController;
  72431. })(BABYLON || (BABYLON = {}));
  72432. //# sourceMappingURL=babylon.gearVRController.js.map
  72433. var BABYLON;
  72434. (function (BABYLON) {
  72435. /**
  72436. * Google Daydream controller
  72437. */
  72438. var DaydreamController = /** @class */ (function (_super) {
  72439. __extends(DaydreamController, _super);
  72440. /**
  72441. * Creates a new DaydreamController from a gamepad
  72442. * @param vrGamepad the gamepad that the controller should be created from
  72443. */
  72444. function DaydreamController(vrGamepad) {
  72445. var _this = _super.call(this, vrGamepad) || this;
  72446. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72447. return _this;
  72448. }
  72449. /**
  72450. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72451. * @param scene scene in which to add meshes
  72452. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72453. */
  72454. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72455. var _this = this;
  72456. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72457. _this._defaultModel = newMeshes[1];
  72458. _this.attachToMesh(_this._defaultModel);
  72459. if (meshLoaded) {
  72460. meshLoaded(_this._defaultModel);
  72461. }
  72462. });
  72463. };
  72464. /**
  72465. * Called once for each button that changed state since the last frame
  72466. * @param buttonIdx Which button index changed
  72467. * @param state New state of the button
  72468. * @param changes Which properties on the state changed since last frame
  72469. */
  72470. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72471. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72472. if (buttonIdx === 0) {
  72473. var observable = this.onTriggerStateChangedObservable;
  72474. if (observable) {
  72475. observable.notifyObservers(state);
  72476. }
  72477. }
  72478. else {
  72479. // If the app or home buttons are ever made available
  72480. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72481. }
  72482. };
  72483. /**
  72484. * Base Url for the controller model.
  72485. */
  72486. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72487. /**
  72488. * File name for the controller model.
  72489. */
  72490. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72491. /**
  72492. * Gamepad Id prefix used to identify Daydream Controller.
  72493. */
  72494. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72495. return DaydreamController;
  72496. }(BABYLON.WebVRController));
  72497. BABYLON.DaydreamController = DaydreamController;
  72498. })(BABYLON || (BABYLON = {}));
  72499. //# sourceMappingURL=babylon.daydreamController.js.map
  72500. var BABYLON;
  72501. (function (BABYLON) {
  72502. var FollowCamera = /** @class */ (function (_super) {
  72503. __extends(FollowCamera, _super);
  72504. function FollowCamera(name, position, scene, lockedTarget) {
  72505. if (lockedTarget === void 0) { lockedTarget = null; }
  72506. var _this = _super.call(this, name, position, scene) || this;
  72507. _this.radius = 12;
  72508. _this.rotationOffset = 0;
  72509. _this.heightOffset = 4;
  72510. _this.cameraAcceleration = 0.05;
  72511. _this.maxCameraSpeed = 20;
  72512. _this.lockedTarget = lockedTarget;
  72513. return _this;
  72514. }
  72515. FollowCamera.prototype.getRadians = function (degrees) {
  72516. return degrees * Math.PI / 180;
  72517. };
  72518. FollowCamera.prototype.follow = function (cameraTarget) {
  72519. if (!cameraTarget)
  72520. return;
  72521. var yRotation;
  72522. if (cameraTarget.rotationQuaternion) {
  72523. var rotMatrix = new BABYLON.Matrix();
  72524. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72525. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72526. }
  72527. else {
  72528. yRotation = cameraTarget.rotation.y;
  72529. }
  72530. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72531. var targetPosition = cameraTarget.getAbsolutePosition();
  72532. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72533. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72534. var dx = targetX - this.position.x;
  72535. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72536. var dz = (targetZ) - this.position.z;
  72537. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72538. var vy = dy * this.cameraAcceleration;
  72539. var vz = dz * this.cameraAcceleration * 2;
  72540. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72541. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72542. }
  72543. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72544. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72545. }
  72546. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72547. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72548. }
  72549. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72550. this.setTarget(targetPosition);
  72551. };
  72552. FollowCamera.prototype._checkInputs = function () {
  72553. _super.prototype._checkInputs.call(this);
  72554. if (this.lockedTarget) {
  72555. this.follow(this.lockedTarget);
  72556. }
  72557. };
  72558. FollowCamera.prototype.getClassName = function () {
  72559. return "FollowCamera";
  72560. };
  72561. __decorate([
  72562. BABYLON.serialize()
  72563. ], FollowCamera.prototype, "radius", void 0);
  72564. __decorate([
  72565. BABYLON.serialize()
  72566. ], FollowCamera.prototype, "rotationOffset", void 0);
  72567. __decorate([
  72568. BABYLON.serialize()
  72569. ], FollowCamera.prototype, "heightOffset", void 0);
  72570. __decorate([
  72571. BABYLON.serialize()
  72572. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72573. __decorate([
  72574. BABYLON.serialize()
  72575. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72576. __decorate([
  72577. BABYLON.serializeAsMeshReference("lockedTargetId")
  72578. ], FollowCamera.prototype, "lockedTarget", void 0);
  72579. return FollowCamera;
  72580. }(BABYLON.TargetCamera));
  72581. BABYLON.FollowCamera = FollowCamera;
  72582. var ArcFollowCamera = /** @class */ (function (_super) {
  72583. __extends(ArcFollowCamera, _super);
  72584. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72585. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72586. _this.alpha = alpha;
  72587. _this.beta = beta;
  72588. _this.radius = radius;
  72589. _this.target = target;
  72590. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72591. _this.follow();
  72592. return _this;
  72593. }
  72594. ArcFollowCamera.prototype.follow = function () {
  72595. if (!this.target) {
  72596. return;
  72597. }
  72598. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72599. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72600. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72601. var targetPosition = this.target.getAbsolutePosition();
  72602. this.position = targetPosition.add(this._cartesianCoordinates);
  72603. this.setTarget(targetPosition);
  72604. };
  72605. ArcFollowCamera.prototype._checkInputs = function () {
  72606. _super.prototype._checkInputs.call(this);
  72607. this.follow();
  72608. };
  72609. ArcFollowCamera.prototype.getClassName = function () {
  72610. return "ArcFollowCamera";
  72611. };
  72612. return ArcFollowCamera;
  72613. }(BABYLON.TargetCamera));
  72614. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72615. })(BABYLON || (BABYLON = {}));
  72616. //# sourceMappingURL=babylon.followCamera.js.map
  72617. var BABYLON;
  72618. (function (BABYLON) {
  72619. // We're mainly based on the logic defined into the FreeCamera code
  72620. var UniversalCamera = /** @class */ (function (_super) {
  72621. __extends(UniversalCamera, _super);
  72622. //-- end properties for backward compatibility for inputs
  72623. function UniversalCamera(name, position, scene) {
  72624. var _this = _super.call(this, name, position, scene) || this;
  72625. _this.inputs.addGamepad();
  72626. return _this;
  72627. }
  72628. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72629. //-- Begin properties for backward compatibility for inputs
  72630. get: function () {
  72631. var gamepad = this.inputs.attached["gamepad"];
  72632. if (gamepad)
  72633. return gamepad.gamepadAngularSensibility;
  72634. return 0;
  72635. },
  72636. set: function (value) {
  72637. var gamepad = this.inputs.attached["gamepad"];
  72638. if (gamepad)
  72639. gamepad.gamepadAngularSensibility = value;
  72640. },
  72641. enumerable: true,
  72642. configurable: true
  72643. });
  72644. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72645. get: function () {
  72646. var gamepad = this.inputs.attached["gamepad"];
  72647. if (gamepad)
  72648. return gamepad.gamepadMoveSensibility;
  72649. return 0;
  72650. },
  72651. set: function (value) {
  72652. var gamepad = this.inputs.attached["gamepad"];
  72653. if (gamepad)
  72654. gamepad.gamepadMoveSensibility = value;
  72655. },
  72656. enumerable: true,
  72657. configurable: true
  72658. });
  72659. UniversalCamera.prototype.getClassName = function () {
  72660. return "UniversalCamera";
  72661. };
  72662. return UniversalCamera;
  72663. }(BABYLON.TouchCamera));
  72664. BABYLON.UniversalCamera = UniversalCamera;
  72665. })(BABYLON || (BABYLON = {}));
  72666. //# sourceMappingURL=babylon.universalCamera.js.map
  72667. var BABYLON;
  72668. (function (BABYLON) {
  72669. // We're mainly based on the logic defined into the FreeCamera code
  72670. var GamepadCamera = /** @class */ (function (_super) {
  72671. __extends(GamepadCamera, _super);
  72672. //-- end properties for backward compatibility for inputs
  72673. function GamepadCamera(name, position, scene) {
  72674. return _super.call(this, name, position, scene) || this;
  72675. }
  72676. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72677. //-- Begin properties for backward compatibility for inputs
  72678. get: function () {
  72679. var gamepad = this.inputs.attached["gamepad"];
  72680. if (gamepad)
  72681. return gamepad.gamepadAngularSensibility;
  72682. return 0;
  72683. },
  72684. set: function (value) {
  72685. var gamepad = this.inputs.attached["gamepad"];
  72686. if (gamepad)
  72687. gamepad.gamepadAngularSensibility = value;
  72688. },
  72689. enumerable: true,
  72690. configurable: true
  72691. });
  72692. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72693. get: function () {
  72694. var gamepad = this.inputs.attached["gamepad"];
  72695. if (gamepad)
  72696. return gamepad.gamepadMoveSensibility;
  72697. return 0;
  72698. },
  72699. set: function (value) {
  72700. var gamepad = this.inputs.attached["gamepad"];
  72701. if (gamepad)
  72702. gamepad.gamepadMoveSensibility = value;
  72703. },
  72704. enumerable: true,
  72705. configurable: true
  72706. });
  72707. GamepadCamera.prototype.getClassName = function () {
  72708. return "GamepadCamera";
  72709. };
  72710. return GamepadCamera;
  72711. }(BABYLON.UniversalCamera));
  72712. BABYLON.GamepadCamera = GamepadCamera;
  72713. })(BABYLON || (BABYLON = {}));
  72714. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72715. var BABYLON;
  72716. (function (BABYLON) {
  72717. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72718. function PostProcessRenderPipelineManager() {
  72719. this._renderPipelines = {};
  72720. }
  72721. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72722. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72723. };
  72724. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72725. if (unique === void 0) { unique = false; }
  72726. var renderPipeline = this._renderPipelines[renderPipelineName];
  72727. if (!renderPipeline) {
  72728. return;
  72729. }
  72730. renderPipeline._attachCameras(cameras, unique);
  72731. };
  72732. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72733. var renderPipeline = this._renderPipelines[renderPipelineName];
  72734. if (!renderPipeline) {
  72735. return;
  72736. }
  72737. renderPipeline._detachCameras(cameras);
  72738. };
  72739. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72740. var renderPipeline = this._renderPipelines[renderPipelineName];
  72741. if (!renderPipeline) {
  72742. return;
  72743. }
  72744. renderPipeline._enableEffect(renderEffectName, cameras);
  72745. };
  72746. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72747. var renderPipeline = this._renderPipelines[renderPipelineName];
  72748. if (!renderPipeline) {
  72749. return;
  72750. }
  72751. renderPipeline._disableEffect(renderEffectName, cameras);
  72752. };
  72753. PostProcessRenderPipelineManager.prototype.update = function () {
  72754. for (var renderPipelineName in this._renderPipelines) {
  72755. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72756. var pipeline = this._renderPipelines[renderPipelineName];
  72757. if (!pipeline.isSupported) {
  72758. pipeline.dispose();
  72759. delete this._renderPipelines[renderPipelineName];
  72760. }
  72761. else {
  72762. pipeline._update();
  72763. }
  72764. }
  72765. }
  72766. };
  72767. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72768. for (var renderPipelineName in this._renderPipelines) {
  72769. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72770. var pipeline = this._renderPipelines[renderPipelineName];
  72771. pipeline._rebuild();
  72772. }
  72773. }
  72774. };
  72775. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72776. for (var renderPipelineName in this._renderPipelines) {
  72777. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72778. var pipeline = this._renderPipelines[renderPipelineName];
  72779. pipeline.dispose();
  72780. }
  72781. }
  72782. };
  72783. return PostProcessRenderPipelineManager;
  72784. }());
  72785. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72786. })(BABYLON || (BABYLON = {}));
  72787. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72788. var BABYLON;
  72789. (function (BABYLON) {
  72790. /**
  72791. * This represents a set of one or more post processes in Babylon.
  72792. * A post process can be used to apply a shader to a texture after it is rendered.
  72793. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72794. */
  72795. var PostProcessRenderEffect = /** @class */ (function () {
  72796. /**
  72797. * Instantiates a post process render effect.
  72798. * A post process can be used to apply a shader to a texture after it is rendered.
  72799. * @param engine The engine the effect is tied to
  72800. * @param name The name of the effect
  72801. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72802. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72803. */
  72804. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72805. this._name = name;
  72806. this._singleInstance = singleInstance || true;
  72807. this._getPostProcesses = getPostProcesses;
  72808. this._cameras = {};
  72809. this._indicesForCamera = {};
  72810. this._postProcesses = {};
  72811. }
  72812. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72813. /**
  72814. * Checks if all the post processes in the effect are supported.
  72815. */
  72816. get: function () {
  72817. for (var index in this._postProcesses) {
  72818. if (this._postProcesses.hasOwnProperty(index)) {
  72819. var pps = this._postProcesses[index];
  72820. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72821. if (!pps[ppIndex].isSupported) {
  72822. return false;
  72823. }
  72824. }
  72825. }
  72826. }
  72827. return true;
  72828. },
  72829. enumerable: true,
  72830. configurable: true
  72831. });
  72832. /**
  72833. * Updates the current state of the effect
  72834. */
  72835. PostProcessRenderEffect.prototype._update = function () {
  72836. };
  72837. /**
  72838. * Attaches the effect on cameras
  72839. * @param cameras The camera to attach to.
  72840. */
  72841. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72842. var _this = this;
  72843. var cameraKey;
  72844. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72845. if (!cams) {
  72846. return;
  72847. }
  72848. for (var i = 0; i < cams.length; i++) {
  72849. var camera = cams[i];
  72850. var cameraName = camera.name;
  72851. if (this._singleInstance) {
  72852. cameraKey = 0;
  72853. }
  72854. else {
  72855. cameraKey = cameraName;
  72856. }
  72857. if (!this._postProcesses[cameraKey]) {
  72858. var postProcess = this._getPostProcesses();
  72859. if (postProcess) {
  72860. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72861. }
  72862. }
  72863. if (!this._indicesForCamera[cameraName]) {
  72864. this._indicesForCamera[cameraName] = [];
  72865. }
  72866. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72867. var index = camera.attachPostProcess(postProcess);
  72868. _this._indicesForCamera[cameraName].push(index);
  72869. });
  72870. if (!this._cameras[cameraName]) {
  72871. this._cameras[cameraName] = camera;
  72872. }
  72873. }
  72874. };
  72875. /**
  72876. * Detatches the effect on cameras
  72877. * @param cameras The camera to detatch from.
  72878. */
  72879. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72880. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72881. if (!cams) {
  72882. return;
  72883. }
  72884. for (var i = 0; i < cams.length; i++) {
  72885. var camera = cams[i];
  72886. var cameraName = camera.name;
  72887. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72888. camera.detachPostProcess(postProcess);
  72889. });
  72890. if (this._cameras[cameraName]) {
  72891. //this._indicesForCamera.splice(index, 1);
  72892. this._cameras[cameraName] = null;
  72893. }
  72894. }
  72895. };
  72896. /**
  72897. * Enables the effect on given cameras
  72898. * @param cameras The camera to enable.
  72899. */
  72900. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72901. var _this = this;
  72902. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72903. if (!cams) {
  72904. return;
  72905. }
  72906. for (var i = 0; i < cams.length; i++) {
  72907. var camera = cams[i];
  72908. var cameraName = camera.name;
  72909. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72910. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72911. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72912. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72913. });
  72914. }
  72915. }
  72916. }
  72917. };
  72918. /**
  72919. * Disables the effect on the given cameras
  72920. * @param cameras The camera to disable.
  72921. */
  72922. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72923. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72924. if (!cams) {
  72925. return;
  72926. }
  72927. for (var i = 0; i < cams.length; i++) {
  72928. var camera = cams[i];
  72929. var cameraName = camera.name;
  72930. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72931. camera.detachPostProcess(postProcess);
  72932. });
  72933. }
  72934. };
  72935. /**
  72936. * Gets a list of the post processes contained in the effect.
  72937. * @param camera The camera to get the post processes on.
  72938. * @returns The list of the post processes in the effect.
  72939. */
  72940. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72941. if (this._singleInstance) {
  72942. return this._postProcesses[0];
  72943. }
  72944. else {
  72945. if (!camera) {
  72946. return null;
  72947. }
  72948. return this._postProcesses[camera.name];
  72949. }
  72950. };
  72951. return PostProcessRenderEffect;
  72952. }());
  72953. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72954. })(BABYLON || (BABYLON = {}));
  72955. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72956. var BABYLON;
  72957. (function (BABYLON) {
  72958. var PostProcessRenderPipeline = /** @class */ (function () {
  72959. function PostProcessRenderPipeline(engine, name) {
  72960. this.engine = engine;
  72961. this._name = name;
  72962. this._renderEffects = {};
  72963. this._renderEffectsForIsolatedPass = new Array();
  72964. this._cameras = [];
  72965. }
  72966. PostProcessRenderPipeline.prototype.getClassName = function () {
  72967. return "PostProcessRenderPipeline";
  72968. };
  72969. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72970. get: function () {
  72971. for (var renderEffectName in this._renderEffects) {
  72972. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72973. if (!this._renderEffects[renderEffectName].isSupported) {
  72974. return false;
  72975. }
  72976. }
  72977. }
  72978. return true;
  72979. },
  72980. enumerable: true,
  72981. configurable: true
  72982. });
  72983. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72984. this._renderEffects[renderEffect._name] = renderEffect;
  72985. };
  72986. // private
  72987. PostProcessRenderPipeline.prototype._rebuild = function () {
  72988. };
  72989. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72990. var renderEffects = this._renderEffects[renderEffectName];
  72991. if (!renderEffects) {
  72992. return;
  72993. }
  72994. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72995. };
  72996. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72997. var renderEffects = this._renderEffects[renderEffectName];
  72998. if (!renderEffects) {
  72999. return;
  73000. }
  73001. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73002. };
  73003. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73004. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73005. if (!cams) {
  73006. return;
  73007. }
  73008. var indicesToDelete = [];
  73009. var i;
  73010. for (i = 0; i < cams.length; i++) {
  73011. var camera = cams[i];
  73012. var cameraName = camera.name;
  73013. if (this._cameras.indexOf(camera) === -1) {
  73014. this._cameras[cameraName] = camera;
  73015. }
  73016. else if (unique) {
  73017. indicesToDelete.push(i);
  73018. }
  73019. }
  73020. for (i = 0; i < indicesToDelete.length; i++) {
  73021. cameras.splice(indicesToDelete[i], 1);
  73022. }
  73023. for (var renderEffectName in this._renderEffects) {
  73024. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73025. this._renderEffects[renderEffectName]._attachCameras(cams);
  73026. }
  73027. }
  73028. };
  73029. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73030. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73031. if (!cams) {
  73032. return;
  73033. }
  73034. for (var renderEffectName in this._renderEffects) {
  73035. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73036. this._renderEffects[renderEffectName]._detachCameras(cams);
  73037. }
  73038. }
  73039. for (var i = 0; i < cams.length; i++) {
  73040. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73041. }
  73042. };
  73043. PostProcessRenderPipeline.prototype._update = function () {
  73044. for (var renderEffectName in this._renderEffects) {
  73045. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73046. this._renderEffects[renderEffectName]._update();
  73047. }
  73048. }
  73049. for (var i = 0; i < this._cameras.length; i++) {
  73050. var cameraName = this._cameras[i].name;
  73051. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73052. this._renderEffectsForIsolatedPass[cameraName]._update();
  73053. }
  73054. }
  73055. };
  73056. PostProcessRenderPipeline.prototype._reset = function () {
  73057. this._renderEffects = {};
  73058. this._renderEffectsForIsolatedPass = new Array();
  73059. };
  73060. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73061. // 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)
  73062. var effectKeys = Object.keys(this._renderEffects);
  73063. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73064. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73065. if (postProcesses) {
  73066. postProcesses[0].samples = sampleCount;
  73067. return true;
  73068. }
  73069. }
  73070. return false;
  73071. };
  73072. PostProcessRenderPipeline.prototype.dispose = function () {
  73073. // Must be implemented by children
  73074. };
  73075. __decorate([
  73076. BABYLON.serialize()
  73077. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73078. return PostProcessRenderPipeline;
  73079. }());
  73080. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73081. })(BABYLON || (BABYLON = {}));
  73082. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73083. var BABYLON;
  73084. (function (BABYLON) {
  73085. /**
  73086. * This represents a depth renderer in Babylon.
  73087. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73088. */
  73089. var DepthRenderer = /** @class */ (function () {
  73090. /**
  73091. * Instantiates a depth renderer
  73092. * @param scene The scene the renderer belongs to
  73093. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73094. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73095. */
  73096. function DepthRenderer(scene, type, camera) {
  73097. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73098. if (camera === void 0) { camera = null; }
  73099. var _this = this;
  73100. this._scene = scene;
  73101. this._camera = camera;
  73102. var engine = scene.getEngine();
  73103. // Render target
  73104. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73105. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73106. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73107. this._depthMap.refreshRate = 1;
  73108. this._depthMap.renderParticles = false;
  73109. this._depthMap.renderList = null;
  73110. // Camera to get depth map from to support multiple concurrent cameras
  73111. this._depthMap.activeCamera = this._camera;
  73112. this._depthMap.ignoreCameraViewport = true;
  73113. this._depthMap.useCameraPostProcesses = false;
  73114. // set default depth value to 1.0 (far away)
  73115. this._depthMap.onClearObservable.add(function (engine) {
  73116. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73117. });
  73118. // Custom render function
  73119. var renderSubMesh = function (subMesh) {
  73120. var mesh = subMesh.getRenderingMesh();
  73121. var scene = _this._scene;
  73122. var engine = scene.getEngine();
  73123. var material = subMesh.getMaterial();
  73124. if (!material) {
  73125. return;
  73126. }
  73127. // Culling and reverse (right handed system)
  73128. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73129. // Managing instances
  73130. var batch = mesh._getInstancesRenderList(subMesh._id);
  73131. if (batch.mustReturn) {
  73132. return;
  73133. }
  73134. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73135. var camera = _this._camera || scene.activeCamera;
  73136. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73137. engine.enableEffect(_this._effect);
  73138. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73139. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73140. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73141. // Alpha test
  73142. if (material && material.needAlphaTesting()) {
  73143. var alphaTexture = material.getAlphaTestTexture();
  73144. if (alphaTexture) {
  73145. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73146. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73147. }
  73148. }
  73149. // Bones
  73150. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73151. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73152. }
  73153. // Draw
  73154. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73155. }
  73156. };
  73157. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73158. var index;
  73159. if (depthOnlySubMeshes.length) {
  73160. engine.setColorWrite(false);
  73161. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73162. renderSubMesh(depthOnlySubMeshes.data[index]);
  73163. }
  73164. engine.setColorWrite(true);
  73165. }
  73166. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73167. renderSubMesh(opaqueSubMeshes.data[index]);
  73168. }
  73169. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73170. renderSubMesh(alphaTestSubMeshes.data[index]);
  73171. }
  73172. };
  73173. }
  73174. /**
  73175. * Creates the depth rendering effect and checks if the effect is ready.
  73176. * @param subMesh The submesh to be used to render the depth map of
  73177. * @param useInstances If multiple world instances should be used
  73178. * @returns if the depth renderer is ready to render the depth map
  73179. */
  73180. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73181. var material = subMesh.getMaterial();
  73182. if (material.disableDepthWrite) {
  73183. return false;
  73184. }
  73185. var defines = [];
  73186. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73187. var mesh = subMesh.getMesh();
  73188. // Alpha test
  73189. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73190. defines.push("#define ALPHATEST");
  73191. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73192. attribs.push(BABYLON.VertexBuffer.UVKind);
  73193. defines.push("#define UV1");
  73194. }
  73195. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73196. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73197. defines.push("#define UV2");
  73198. }
  73199. }
  73200. // Bones
  73201. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73202. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73203. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73204. if (mesh.numBoneInfluencers > 4) {
  73205. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73206. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73207. }
  73208. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73209. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73210. }
  73211. else {
  73212. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73213. }
  73214. // Instances
  73215. if (useInstances) {
  73216. defines.push("#define INSTANCES");
  73217. attribs.push("world0");
  73218. attribs.push("world1");
  73219. attribs.push("world2");
  73220. attribs.push("world3");
  73221. }
  73222. // Get correct effect
  73223. var join = defines.join("\n");
  73224. if (this._cachedDefines !== join) {
  73225. this._cachedDefines = join;
  73226. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73227. }
  73228. return this._effect.isReady();
  73229. };
  73230. /**
  73231. * Gets the texture which the depth map will be written to.
  73232. * @returns The depth map texture
  73233. */
  73234. DepthRenderer.prototype.getDepthMap = function () {
  73235. return this._depthMap;
  73236. };
  73237. /**
  73238. * Disposes of the depth renderer.
  73239. */
  73240. DepthRenderer.prototype.dispose = function () {
  73241. this._depthMap.dispose();
  73242. };
  73243. return DepthRenderer;
  73244. }());
  73245. BABYLON.DepthRenderer = DepthRenderer;
  73246. })(BABYLON || (BABYLON = {}));
  73247. //# sourceMappingURL=babylon.depthRenderer.js.map
  73248. var BABYLON;
  73249. (function (BABYLON) {
  73250. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73251. __extends(SSAORenderingPipeline, _super);
  73252. /**
  73253. * @constructor
  73254. * @param {string} name - The rendering pipeline name
  73255. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73256. * @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 }
  73257. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73258. */
  73259. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73260. var _this = _super.call(this, scene.getEngine(), name) || this;
  73261. // Members
  73262. /**
  73263. * The PassPostProcess id in the pipeline that contains the original scene color
  73264. */
  73265. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73266. /**
  73267. * The SSAO PostProcess id in the pipeline
  73268. */
  73269. _this.SSAORenderEffect = "SSAORenderEffect";
  73270. /**
  73271. * The horizontal blur PostProcess id in the pipeline
  73272. */
  73273. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73274. /**
  73275. * The vertical blur PostProcess id in the pipeline
  73276. */
  73277. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73278. /**
  73279. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73280. */
  73281. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73282. /**
  73283. * The output strength of the SSAO post-process. Default value is 1.0.
  73284. */
  73285. _this.totalStrength = 1.0;
  73286. /**
  73287. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73288. */
  73289. _this.radius = 0.0001;
  73290. /**
  73291. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73292. * Must not be equal to fallOff and superior to fallOff.
  73293. * Default value is 0.975
  73294. */
  73295. _this.area = 0.0075;
  73296. /**
  73297. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73298. * Must not be equal to area and inferior to area.
  73299. * Default value is 0.0
  73300. */
  73301. _this.fallOff = 0.000001;
  73302. /**
  73303. * The base color of the SSAO post-process
  73304. * The final result is "base + ssao" between [0, 1]
  73305. */
  73306. _this.base = 0.5;
  73307. _this._firstUpdate = true;
  73308. _this._scene = scene;
  73309. // Set up assets
  73310. _this._createRandomTexture();
  73311. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73312. var ssaoRatio = ratio.ssaoRatio || ratio;
  73313. var combineRatio = ratio.combineRatio || ratio;
  73314. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73315. _this._createSSAOPostProcess(ssaoRatio);
  73316. _this._createBlurPostProcess(ssaoRatio);
  73317. _this._createSSAOCombinePostProcess(combineRatio);
  73318. // Set up pipeline
  73319. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73320. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73321. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73322. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73323. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73324. // Finish
  73325. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73326. if (cameras)
  73327. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73328. return _this;
  73329. }
  73330. // Public Methods
  73331. /**
  73332. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73333. */
  73334. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73335. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73336. for (var i = 0; i < this._scene.cameras.length; i++) {
  73337. var camera = this._scene.cameras[i];
  73338. this._originalColorPostProcess.dispose(camera);
  73339. this._ssaoPostProcess.dispose(camera);
  73340. this._blurHPostProcess.dispose(camera);
  73341. this._blurVPostProcess.dispose(camera);
  73342. this._ssaoCombinePostProcess.dispose(camera);
  73343. }
  73344. this._randomTexture.dispose();
  73345. if (disableDepthRender)
  73346. this._scene.disableDepthRenderer();
  73347. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73348. _super.prototype.dispose.call(this);
  73349. };
  73350. // Private Methods
  73351. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73352. var _this = this;
  73353. var size = 16;
  73354. 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);
  73355. 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);
  73356. this._blurHPostProcess.onActivateObservable.add(function () {
  73357. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73358. _this._blurHPostProcess.kernel = size * dw;
  73359. });
  73360. this._blurVPostProcess.onActivateObservable.add(function () {
  73361. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73362. _this._blurVPostProcess.kernel = size * dw;
  73363. });
  73364. };
  73365. SSAORenderingPipeline.prototype._rebuild = function () {
  73366. this._firstUpdate = true;
  73367. _super.prototype._rebuild.call(this);
  73368. };
  73369. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73370. var _this = this;
  73371. var numSamples = 16;
  73372. var sampleSphere = [
  73373. 0.5381, 0.1856, -0.4319,
  73374. 0.1379, 0.2486, 0.4430,
  73375. 0.3371, 0.5679, -0.0057,
  73376. -0.6999, -0.0451, -0.0019,
  73377. 0.0689, -0.1598, -0.8547,
  73378. 0.0560, 0.0069, -0.1843,
  73379. -0.0146, 0.1402, 0.0762,
  73380. 0.0100, -0.1924, -0.0344,
  73381. -0.3577, -0.5301, -0.4358,
  73382. -0.3169, 0.1063, 0.0158,
  73383. 0.0103, -0.5869, 0.0046,
  73384. -0.0897, -0.4940, 0.3287,
  73385. 0.7119, -0.0154, -0.0918,
  73386. -0.0533, 0.0596, -0.5411,
  73387. 0.0352, -0.0631, 0.5460,
  73388. -0.4776, 0.2847, -0.0271
  73389. ];
  73390. var samplesFactor = 1.0 / numSamples;
  73391. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73392. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73393. "area", "fallOff", "base", "range", "viewport"
  73394. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73395. this._ssaoPostProcess.onApply = function (effect) {
  73396. if (_this._firstUpdate) {
  73397. effect.setArray3("sampleSphere", sampleSphere);
  73398. effect.setFloat("samplesFactor", samplesFactor);
  73399. effect.setFloat("randTextureTiles", 4.0);
  73400. }
  73401. effect.setFloat("totalStrength", _this.totalStrength);
  73402. effect.setFloat("radius", _this.radius);
  73403. effect.setFloat("area", _this.area);
  73404. effect.setFloat("fallOff", _this.fallOff);
  73405. effect.setFloat("base", _this.base);
  73406. effect.setTexture("textureSampler", _this._depthTexture);
  73407. effect.setTexture("randomSampler", _this._randomTexture);
  73408. };
  73409. };
  73410. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73411. var _this = this;
  73412. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73413. this._ssaoCombinePostProcess.onApply = function (effect) {
  73414. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73415. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73416. };
  73417. };
  73418. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73419. var size = 512;
  73420. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73421. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73422. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73423. var context = this._randomTexture.getContext();
  73424. var rand = function (min, max) {
  73425. return Math.random() * (max - min) + min;
  73426. };
  73427. var randVector = BABYLON.Vector3.Zero();
  73428. for (var x = 0; x < size; x++) {
  73429. for (var y = 0; y < size; y++) {
  73430. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73431. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73432. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73433. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73434. context.fillRect(x, y, 1, 1);
  73435. }
  73436. }
  73437. this._randomTexture.update(false);
  73438. };
  73439. __decorate([
  73440. BABYLON.serialize()
  73441. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73442. __decorate([
  73443. BABYLON.serialize()
  73444. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73445. __decorate([
  73446. BABYLON.serialize()
  73447. ], SSAORenderingPipeline.prototype, "area", void 0);
  73448. __decorate([
  73449. BABYLON.serialize()
  73450. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73451. __decorate([
  73452. BABYLON.serialize()
  73453. ], SSAORenderingPipeline.prototype, "base", void 0);
  73454. return SSAORenderingPipeline;
  73455. }(BABYLON.PostProcessRenderPipeline));
  73456. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73457. })(BABYLON || (BABYLON = {}));
  73458. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73459. var BABYLON;
  73460. (function (BABYLON) {
  73461. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73462. __extends(SSAO2RenderingPipeline, _super);
  73463. /**
  73464. * @constructor
  73465. * @param {string} name - The rendering pipeline name
  73466. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73467. * @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 }
  73468. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73469. */
  73470. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73471. var _this = _super.call(this, scene.getEngine(), name) || this;
  73472. // Members
  73473. /**
  73474. * The PassPostProcess id in the pipeline that contains the original scene color
  73475. */
  73476. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73477. /**
  73478. * The SSAO PostProcess id in the pipeline
  73479. */
  73480. _this.SSAORenderEffect = "SSAORenderEffect";
  73481. /**
  73482. * The horizontal blur PostProcess id in the pipeline
  73483. */
  73484. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73485. /**
  73486. * The vertical blur PostProcess id in the pipeline
  73487. */
  73488. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73489. /**
  73490. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73491. */
  73492. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73493. /**
  73494. * The output strength of the SSAO post-process. Default value is 1.0.
  73495. */
  73496. _this.totalStrength = 1.0;
  73497. /**
  73498. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73499. */
  73500. _this.maxZ = 100.0;
  73501. /**
  73502. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73503. */
  73504. _this.minZAspect = 0.2;
  73505. /**
  73506. * Number of samples used for the SSAO calculations. Default value is 8
  73507. */
  73508. _this._samples = 8;
  73509. /**
  73510. * Are we using bilateral blur ?
  73511. */
  73512. _this._expensiveBlur = true;
  73513. /**
  73514. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73515. */
  73516. _this.radius = 2.0;
  73517. /**
  73518. * The base color of the SSAO post-process
  73519. * The final result is "base + ssao" between [0, 1]
  73520. */
  73521. _this.base = 0.1;
  73522. _this._firstUpdate = true;
  73523. _this._scene = scene;
  73524. _this._ratio = ratio;
  73525. if (!_this.isSupported) {
  73526. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73527. return _this;
  73528. }
  73529. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73530. var blurRatio = _this._ratio.blurRatio || ratio;
  73531. // Set up assets
  73532. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73533. _this._createRandomTexture();
  73534. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73535. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73536. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73537. _this._createSSAOPostProcess(1.0);
  73538. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73539. _this._createSSAOCombinePostProcess(blurRatio);
  73540. // Set up pipeline
  73541. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73542. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73543. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73544. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73545. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73546. // Finish
  73547. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73548. if (cameras)
  73549. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73550. return _this;
  73551. }
  73552. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73553. get: function () {
  73554. return this._samples;
  73555. },
  73556. set: function (n) {
  73557. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73558. this._samples = n;
  73559. this._sampleSphere = this._generateHemisphere();
  73560. this._firstUpdate = true;
  73561. },
  73562. enumerable: true,
  73563. configurable: true
  73564. });
  73565. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73566. get: function () {
  73567. return this._expensiveBlur;
  73568. },
  73569. set: function (b) {
  73570. 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"]);
  73571. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73572. this._expensiveBlur = b;
  73573. this._firstUpdate = true;
  73574. },
  73575. enumerable: true,
  73576. configurable: true
  73577. });
  73578. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73579. /**
  73580. * Support test.
  73581. */
  73582. get: function () {
  73583. var engine = BABYLON.Engine.LastCreatedEngine;
  73584. if (!engine) {
  73585. return false;
  73586. }
  73587. return engine.getCaps().drawBuffersExtension;
  73588. },
  73589. enumerable: true,
  73590. configurable: true
  73591. });
  73592. // Public Methods
  73593. /**
  73594. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73595. */
  73596. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73597. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73598. for (var i = 0; i < this._scene.cameras.length; i++) {
  73599. var camera = this._scene.cameras[i];
  73600. this._originalColorPostProcess.dispose(camera);
  73601. this._ssaoPostProcess.dispose(camera);
  73602. this._blurHPostProcess.dispose(camera);
  73603. this._blurVPostProcess.dispose(camera);
  73604. this._ssaoCombinePostProcess.dispose(camera);
  73605. }
  73606. this._randomTexture.dispose();
  73607. if (disableGeometryBufferRenderer)
  73608. this._scene.disableGeometryBufferRenderer();
  73609. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73610. _super.prototype.dispose.call(this);
  73611. };
  73612. // Private Methods
  73613. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73614. var _this = this;
  73615. this._samplerOffsets = [];
  73616. var expensive = this.expensiveBlur;
  73617. for (var i = -8; i < 8; i++) {
  73618. this._samplerOffsets.push(i * 2 + 0.5);
  73619. }
  73620. 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");
  73621. this._blurHPostProcess.onApply = function (effect) {
  73622. if (!_this._scene.activeCamera) {
  73623. return;
  73624. }
  73625. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73626. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73627. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73628. effect.setFloat("radius", _this.radius);
  73629. effect.setTexture("depthSampler", _this._depthTexture);
  73630. if (_this._firstUpdate) {
  73631. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73632. }
  73633. };
  73634. 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");
  73635. this._blurVPostProcess.onApply = function (effect) {
  73636. if (!_this._scene.activeCamera) {
  73637. return;
  73638. }
  73639. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73640. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73641. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73642. effect.setFloat("radius", _this.radius);
  73643. effect.setTexture("depthSampler", _this._depthTexture);
  73644. if (_this._firstUpdate) {
  73645. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73646. _this._firstUpdate = false;
  73647. }
  73648. };
  73649. };
  73650. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73651. this._firstUpdate = true;
  73652. _super.prototype._rebuild.call(this);
  73653. };
  73654. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73655. var numSamples = this.samples;
  73656. var result = [];
  73657. var vector, scale;
  73658. var rand = function (min, max) {
  73659. return Math.random() * (max - min) + min;
  73660. };
  73661. var i = 0;
  73662. while (i < numSamples) {
  73663. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73664. vector.normalize();
  73665. scale = i / numSamples;
  73666. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73667. vector.scaleInPlace(scale);
  73668. result.push(vector.x, vector.y, vector.z);
  73669. i++;
  73670. }
  73671. return result;
  73672. };
  73673. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73674. var _this = this;
  73675. var numSamples = this.samples;
  73676. this._sampleSphere = this._generateHemisphere();
  73677. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73678. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73679. "base", "range", "projection", "near", "far", "texelSize",
  73680. "xViewport", "yViewport", "maxZ", "minZAspect"
  73681. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73682. this._ssaoPostProcess.onApply = function (effect) {
  73683. if (_this._firstUpdate) {
  73684. effect.setArray3("sampleSphere", _this._sampleSphere);
  73685. effect.setFloat("randTextureTiles", 4.0);
  73686. }
  73687. if (!_this._scene.activeCamera) {
  73688. return;
  73689. }
  73690. effect.setFloat("samplesFactor", 1 / _this.samples);
  73691. effect.setFloat("totalStrength", _this.totalStrength);
  73692. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73693. effect.setFloat("radius", _this.radius);
  73694. effect.setFloat("maxZ", _this.maxZ);
  73695. effect.setFloat("minZAspect", _this.minZAspect);
  73696. effect.setFloat("base", _this.base);
  73697. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73698. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73699. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73700. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73701. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73702. effect.setTexture("textureSampler", _this._depthTexture);
  73703. effect.setTexture("normalSampler", _this._normalTexture);
  73704. effect.setTexture("randomSampler", _this._randomTexture);
  73705. };
  73706. };
  73707. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73708. var _this = this;
  73709. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73710. this._ssaoCombinePostProcess.onApply = function (effect) {
  73711. var viewport = _this._scene.activeCamera.viewport;
  73712. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  73713. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73714. };
  73715. };
  73716. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73717. var size = 512;
  73718. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73719. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73720. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73721. var context = this._randomTexture.getContext();
  73722. var rand = function (min, max) {
  73723. return Math.random() * (max - min) + min;
  73724. };
  73725. var randVector = BABYLON.Vector3.Zero();
  73726. for (var x = 0; x < size; x++) {
  73727. for (var y = 0; y < size; y++) {
  73728. randVector.x = rand(0.0, 1.0);
  73729. randVector.y = rand(0.0, 1.0);
  73730. randVector.z = 0.0;
  73731. randVector.normalize();
  73732. randVector.scaleInPlace(255);
  73733. randVector.x = Math.floor(randVector.x);
  73734. randVector.y = Math.floor(randVector.y);
  73735. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73736. context.fillRect(x, y, 1, 1);
  73737. }
  73738. }
  73739. this._randomTexture.update(false);
  73740. };
  73741. /**
  73742. * Serialize the rendering pipeline (Used when exporting)
  73743. * @returns the serialized object
  73744. */
  73745. SSAO2RenderingPipeline.prototype.serialize = function () {
  73746. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73747. serializationObject.customType = "SSAO2RenderingPipeline";
  73748. return serializationObject;
  73749. };
  73750. /**
  73751. * Parse the serialized pipeline
  73752. * @param source Source pipeline.
  73753. * @param scene The scene to load the pipeline to.
  73754. * @param rootUrl The URL of the serialized pipeline.
  73755. * @returns An instantiated pipeline from the serialized object.
  73756. */
  73757. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73758. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73759. };
  73760. __decorate([
  73761. BABYLON.serialize()
  73762. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73763. __decorate([
  73764. BABYLON.serialize()
  73765. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73766. __decorate([
  73767. BABYLON.serialize()
  73768. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73769. __decorate([
  73770. BABYLON.serialize("samples")
  73771. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73772. __decorate([
  73773. BABYLON.serialize()
  73774. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73775. __decorate([
  73776. BABYLON.serialize("expensiveBlur")
  73777. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73778. __decorate([
  73779. BABYLON.serialize()
  73780. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73781. __decorate([
  73782. BABYLON.serialize()
  73783. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73784. return SSAO2RenderingPipeline;
  73785. }(BABYLON.PostProcessRenderPipeline));
  73786. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73787. })(BABYLON || (BABYLON = {}));
  73788. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73789. // BABYLON.JS Chromatic Aberration GLSL Shader
  73790. // Author: Olivier Guyot
  73791. // Separates very slightly R, G and B colors on the edges of the screen
  73792. // Inspired by Francois Tarlier & Martins Upitis
  73793. var BABYLON;
  73794. (function (BABYLON) {
  73795. var LensRenderingPipeline = /** @class */ (function (_super) {
  73796. __extends(LensRenderingPipeline, _super);
  73797. /**
  73798. * @constructor
  73799. *
  73800. * Effect parameters are as follow:
  73801. * {
  73802. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73803. * edge_blur: number; // from 0 to x (1 for realism)
  73804. * distortion: number; // from 0 to x (1 for realism)
  73805. * grain_amount: number; // from 0 to 1
  73806. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73807. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73808. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73809. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73810. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73811. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73812. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73813. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73814. * }
  73815. * Note: if an effect parameter is unset, effect is disabled
  73816. *
  73817. * @param {string} name - The rendering pipeline name
  73818. * @param {object} parameters - An object containing all parameters (see above)
  73819. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73820. * @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)
  73821. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73822. */
  73823. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73824. if (ratio === void 0) { ratio = 1.0; }
  73825. var _this = _super.call(this, scene.getEngine(), name) || this;
  73826. // Lens effects can be of the following:
  73827. // - chromatic aberration (slight shift of RGB colors)
  73828. // - blur on the edge of the lens
  73829. // - lens distortion
  73830. // - depth-of-field blur & highlights enhancing
  73831. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73832. // - grain effect (noise or custom texture)
  73833. // Two additional texture samplers are needed:
  73834. // - depth map (for depth-of-field)
  73835. // - grain texture
  73836. /**
  73837. * The chromatic aberration PostProcess id in the pipeline
  73838. */
  73839. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73840. /**
  73841. * The highlights enhancing PostProcess id in the pipeline
  73842. */
  73843. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73844. /**
  73845. * The depth-of-field PostProcess id in the pipeline
  73846. */
  73847. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73848. _this._scene = scene;
  73849. // Fetch texture samplers
  73850. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73851. if (parameters.grain_texture) {
  73852. _this._grainTexture = parameters.grain_texture;
  73853. }
  73854. else {
  73855. _this._createGrainTexture();
  73856. }
  73857. // save parameters
  73858. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73859. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73860. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73861. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73862. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73863. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73864. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73865. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73866. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73867. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73868. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73869. // Create effects
  73870. _this._createChromaticAberrationPostProcess(ratio);
  73871. _this._createHighlightsPostProcess(ratio);
  73872. _this._createDepthOfFieldPostProcess(ratio / 4);
  73873. // Set up pipeline
  73874. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73875. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73876. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73877. if (_this._highlightsGain === -1) {
  73878. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73879. }
  73880. // Finish
  73881. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73882. if (cameras) {
  73883. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73884. }
  73885. return _this;
  73886. }
  73887. // public methods (self explanatory)
  73888. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73889. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73890. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73891. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73892. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73893. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73894. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73895. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73896. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73897. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73898. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73899. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73900. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73901. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73902. };
  73903. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73904. this._highlightsPostProcess.updateEffect();
  73905. };
  73906. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73907. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73908. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73909. this._highlightsGain = amount;
  73910. };
  73911. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73912. if (this._highlightsGain === -1) {
  73913. this._highlightsGain = 1.0;
  73914. }
  73915. this._highlightsThreshold = amount;
  73916. };
  73917. LensRenderingPipeline.prototype.disableHighlights = function () {
  73918. this._highlightsGain = -1;
  73919. };
  73920. /**
  73921. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73922. */
  73923. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73924. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73925. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73926. this._chromaticAberrationPostProcess = null;
  73927. this._highlightsPostProcess = null;
  73928. this._depthOfFieldPostProcess = null;
  73929. this._grainTexture.dispose();
  73930. if (disableDepthRender)
  73931. this._scene.disableDepthRenderer();
  73932. };
  73933. // colors shifting and distortion
  73934. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73935. var _this = this;
  73936. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73937. [], // samplers
  73938. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73939. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73940. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73941. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73942. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73943. effect.setFloat('radialIntensity', 1);
  73944. effect.setFloat2('direction', 17, 17);
  73945. effect.setFloat2('centerPosition', 0.5, 0.5);
  73946. };
  73947. };
  73948. // highlights enhancing
  73949. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73950. var _this = this;
  73951. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73952. [], // samplers
  73953. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73954. this._highlightsPostProcess.onApply = function (effect) {
  73955. effect.setFloat('gain', _this._highlightsGain);
  73956. effect.setFloat('threshold', _this._highlightsThreshold);
  73957. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73958. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73959. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73960. };
  73961. };
  73962. // colors shifting and distortion
  73963. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73964. var _this = this;
  73965. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73966. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73967. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73968. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73969. this._depthOfFieldPostProcess.onApply = function (effect) {
  73970. effect.setTexture("depthSampler", _this._depthTexture);
  73971. effect.setTexture("grainSampler", _this._grainTexture);
  73972. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73973. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73974. effect.setFloat('grain_amount', _this._grainAmount);
  73975. effect.setBool('blur_noise', _this._blurNoise);
  73976. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73977. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73978. effect.setFloat('distortion', _this._distortion);
  73979. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73980. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73981. effect.setFloat('aperture', _this._dofAperture);
  73982. effect.setFloat('darken', _this._dofDarken);
  73983. effect.setFloat('edge_blur', _this._edgeBlur);
  73984. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73985. if (_this._scene.activeCamera) {
  73986. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73987. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73988. }
  73989. };
  73990. };
  73991. // creates a black and white random noise texture, 512x512
  73992. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73993. var size = 512;
  73994. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73995. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73996. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73997. var context = this._grainTexture.getContext();
  73998. var rand = function (min, max) {
  73999. return Math.random() * (max - min) + min;
  74000. };
  74001. var value;
  74002. for (var x = 0; x < size; x++) {
  74003. for (var y = 0; y < size; y++) {
  74004. value = Math.floor(rand(0.42, 0.58) * 255);
  74005. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74006. context.fillRect(x, y, 1, 1);
  74007. }
  74008. }
  74009. this._grainTexture.update(false);
  74010. };
  74011. return LensRenderingPipeline;
  74012. }(BABYLON.PostProcessRenderPipeline));
  74013. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74014. })(BABYLON || (BABYLON = {}));
  74015. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74016. var BABYLON;
  74017. (function (BABYLON) {
  74018. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74019. __extends(StandardRenderingPipeline, _super);
  74020. /**
  74021. * @constructor
  74022. * @param {string} name - The rendering pipeline name
  74023. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74024. * @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)
  74025. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74026. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74027. */
  74028. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74029. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74030. var _this = _super.call(this, scene.getEngine(), name) || this;
  74031. _this.downSampleX4PostProcess = null;
  74032. _this.brightPassPostProcess = null;
  74033. _this.blurHPostProcesses = [];
  74034. _this.blurVPostProcesses = [];
  74035. _this.textureAdderPostProcess = null;
  74036. _this.volumetricLightPostProcess = null;
  74037. _this.volumetricLightSmoothXPostProcess = null;
  74038. _this.volumetricLightSmoothYPostProcess = null;
  74039. _this.volumetricLightMergePostProces = null;
  74040. _this.volumetricLightFinalPostProcess = null;
  74041. _this.luminancePostProcess = null;
  74042. _this.luminanceDownSamplePostProcesses = [];
  74043. _this.hdrPostProcess = null;
  74044. _this.textureAdderFinalPostProcess = null;
  74045. _this.lensFlareFinalPostProcess = null;
  74046. _this.hdrFinalPostProcess = null;
  74047. _this.lensFlarePostProcess = null;
  74048. _this.lensFlareComposePostProcess = null;
  74049. _this.motionBlurPostProcess = null;
  74050. _this.depthOfFieldPostProcess = null;
  74051. // Values
  74052. _this.brightThreshold = 1.0;
  74053. _this.blurWidth = 512.0;
  74054. _this.horizontalBlur = false;
  74055. _this.exposure = 1.0;
  74056. _this.lensTexture = null;
  74057. _this.volumetricLightCoefficient = 0.2;
  74058. _this.volumetricLightPower = 4.0;
  74059. _this.volumetricLightBlurScale = 64.0;
  74060. _this.sourceLight = null;
  74061. _this.hdrMinimumLuminance = 1.0;
  74062. _this.hdrDecreaseRate = 0.5;
  74063. _this.hdrIncreaseRate = 0.5;
  74064. _this.lensColorTexture = null;
  74065. _this.lensFlareStrength = 20.0;
  74066. _this.lensFlareGhostDispersal = 1.4;
  74067. _this.lensFlareHaloWidth = 0.7;
  74068. _this.lensFlareDistortionStrength = 16.0;
  74069. _this.lensStarTexture = null;
  74070. _this.lensFlareDirtTexture = null;
  74071. _this.depthOfFieldDistance = 10.0;
  74072. _this.depthOfFieldBlurWidth = 64.0;
  74073. _this.motionStrength = 1.0;
  74074. // IAnimatable
  74075. _this.animations = [];
  74076. _this._currentDepthOfFieldSource = null;
  74077. _this._hdrCurrentLuminance = 1.0;
  74078. // Getters and setters
  74079. _this._bloomEnabled = true;
  74080. _this._depthOfFieldEnabled = false;
  74081. _this._vlsEnabled = false;
  74082. _this._lensFlareEnabled = false;
  74083. _this._hdrEnabled = false;
  74084. _this._motionBlurEnabled = false;
  74085. _this._motionBlurSamples = 64.0;
  74086. _this._volumetricLightStepsCount = 50.0;
  74087. _this._cameras = cameras || [];
  74088. // Initialize
  74089. _this._scene = scene;
  74090. _this._basePostProcess = originalPostProcess;
  74091. _this._ratio = ratio;
  74092. // Misc
  74093. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74094. // Finish
  74095. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74096. _this._buildPipeline();
  74097. return _this;
  74098. }
  74099. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74100. get: function () {
  74101. return this._bloomEnabled;
  74102. },
  74103. set: function (enabled) {
  74104. if (this._bloomEnabled === enabled) {
  74105. return;
  74106. }
  74107. this._bloomEnabled = enabled;
  74108. this._buildPipeline();
  74109. },
  74110. enumerable: true,
  74111. configurable: true
  74112. });
  74113. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74114. get: function () {
  74115. return this._depthOfFieldEnabled;
  74116. },
  74117. set: function (enabled) {
  74118. if (this._depthOfFieldEnabled === enabled) {
  74119. return;
  74120. }
  74121. this._depthOfFieldEnabled = enabled;
  74122. this._buildPipeline();
  74123. },
  74124. enumerable: true,
  74125. configurable: true
  74126. });
  74127. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74128. get: function () {
  74129. return this._lensFlareEnabled;
  74130. },
  74131. set: function (enabled) {
  74132. if (this._lensFlareEnabled === enabled) {
  74133. return;
  74134. }
  74135. this._lensFlareEnabled = enabled;
  74136. this._buildPipeline();
  74137. },
  74138. enumerable: true,
  74139. configurable: true
  74140. });
  74141. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74142. get: function () {
  74143. return this._hdrEnabled;
  74144. },
  74145. set: function (enabled) {
  74146. if (this._hdrEnabled === enabled) {
  74147. return;
  74148. }
  74149. this._hdrEnabled = enabled;
  74150. this._buildPipeline();
  74151. },
  74152. enumerable: true,
  74153. configurable: true
  74154. });
  74155. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74156. get: function () {
  74157. return this._vlsEnabled;
  74158. },
  74159. set: function (enabled) {
  74160. if (this._vlsEnabled === enabled) {
  74161. return;
  74162. }
  74163. if (enabled) {
  74164. var geometry = this._scene.enableGeometryBufferRenderer();
  74165. if (!geometry) {
  74166. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74167. return;
  74168. }
  74169. }
  74170. this._vlsEnabled = enabled;
  74171. this._buildPipeline();
  74172. },
  74173. enumerable: true,
  74174. configurable: true
  74175. });
  74176. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74177. get: function () {
  74178. return this._motionBlurEnabled;
  74179. },
  74180. set: function (enabled) {
  74181. if (this._motionBlurEnabled === enabled) {
  74182. return;
  74183. }
  74184. this._motionBlurEnabled = enabled;
  74185. this._buildPipeline();
  74186. },
  74187. enumerable: true,
  74188. configurable: true
  74189. });
  74190. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74191. get: function () {
  74192. return this._volumetricLightStepsCount;
  74193. },
  74194. set: function (count) {
  74195. if (this.volumetricLightPostProcess) {
  74196. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74197. }
  74198. this._volumetricLightStepsCount = count;
  74199. },
  74200. enumerable: true,
  74201. configurable: true
  74202. });
  74203. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74204. get: function () {
  74205. return this._motionBlurSamples;
  74206. },
  74207. set: function (samples) {
  74208. if (this.motionBlurPostProcess) {
  74209. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74210. }
  74211. this._motionBlurSamples = samples;
  74212. },
  74213. enumerable: true,
  74214. configurable: true
  74215. });
  74216. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74217. var _this = this;
  74218. var ratio = this._ratio;
  74219. var scene = this._scene;
  74220. this._disposePostProcesses();
  74221. this._reset();
  74222. // Create pass post-process
  74223. if (!this._basePostProcess) {
  74224. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74225. this.originalPostProcess.onApply = function (effect) {
  74226. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74227. };
  74228. }
  74229. else {
  74230. this.originalPostProcess = this._basePostProcess;
  74231. }
  74232. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74233. this._currentDepthOfFieldSource = this.originalPostProcess;
  74234. if (this._bloomEnabled) {
  74235. // Create down sample X4 post-process
  74236. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74237. // Create bright pass post-process
  74238. this._createBrightPassPostProcess(scene, ratio / 2);
  74239. // Create gaussian blur post-processes (down sampling blurs)
  74240. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74241. // Create texture adder post-process
  74242. this._createTextureAdderPostProcess(scene, ratio);
  74243. // Create depth-of-field source post-process
  74244. 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);
  74245. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74246. }
  74247. if (this._vlsEnabled) {
  74248. // Create volumetric light
  74249. this._createVolumetricLightPostProcess(scene, ratio);
  74250. // Create volumetric light final post-process
  74251. 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);
  74252. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74253. }
  74254. if (this._lensFlareEnabled) {
  74255. // Create lens flare post-process
  74256. this._createLensFlarePostProcess(scene, ratio);
  74257. // Create depth-of-field source post-process post lens-flare and disable it now
  74258. 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);
  74259. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74260. }
  74261. if (this._hdrEnabled) {
  74262. // Create luminance
  74263. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74264. // Create HDR
  74265. this._createHdrPostProcess(scene, ratio);
  74266. // Create depth-of-field source post-process post hdr and disable it now
  74267. 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);
  74268. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74269. }
  74270. if (this._depthOfFieldEnabled) {
  74271. // Create gaussian blur used by depth-of-field
  74272. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74273. // Create depth-of-field post-process
  74274. this._createDepthOfFieldPostProcess(scene, ratio);
  74275. }
  74276. if (this._motionBlurEnabled) {
  74277. // Create motion blur post-process
  74278. this._createMotionBlurPostProcess(scene, ratio);
  74279. }
  74280. if (this._cameras !== null) {
  74281. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74282. }
  74283. };
  74284. // Down Sample X4 Post-Processs
  74285. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74286. var _this = this;
  74287. var downSampleX4Offsets = new Array(32);
  74288. 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);
  74289. this.downSampleX4PostProcess.onApply = function (effect) {
  74290. var id = 0;
  74291. var width = _this.downSampleX4PostProcess.width;
  74292. var height = _this.downSampleX4PostProcess.height;
  74293. for (var i = -2; i < 2; i++) {
  74294. for (var j = -2; j < 2; j++) {
  74295. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74296. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74297. id += 2;
  74298. }
  74299. }
  74300. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74301. };
  74302. // Add to pipeline
  74303. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74304. };
  74305. // Brightpass Post-Process
  74306. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74307. var _this = this;
  74308. var brightOffsets = new Array(8);
  74309. 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);
  74310. this.brightPassPostProcess.onApply = function (effect) {
  74311. var sU = (1.0 / _this.brightPassPostProcess.width);
  74312. var sV = (1.0 / _this.brightPassPostProcess.height);
  74313. brightOffsets[0] = -0.5 * sU;
  74314. brightOffsets[1] = 0.5 * sV;
  74315. brightOffsets[2] = 0.5 * sU;
  74316. brightOffsets[3] = 0.5 * sV;
  74317. brightOffsets[4] = -0.5 * sU;
  74318. brightOffsets[5] = -0.5 * sV;
  74319. brightOffsets[6] = 0.5 * sU;
  74320. brightOffsets[7] = -0.5 * sV;
  74321. effect.setArray2("dsOffsets", brightOffsets);
  74322. effect.setFloat("brightThreshold", _this.brightThreshold);
  74323. };
  74324. // Add to pipeline
  74325. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74326. };
  74327. // Create blur H&V post-processes
  74328. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74329. var _this = this;
  74330. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74331. var engine = scene.getEngine();
  74332. 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);
  74333. 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);
  74334. blurX.onActivateObservable.add(function () {
  74335. var dw = blurX.width / engine.getRenderWidth();
  74336. blurX.kernel = _this[blurWidthKey] * dw;
  74337. });
  74338. blurY.onActivateObservable.add(function () {
  74339. var dw = blurY.height / engine.getRenderHeight();
  74340. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74341. });
  74342. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74343. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74344. this.blurHPostProcesses.push(blurX);
  74345. this.blurVPostProcesses.push(blurY);
  74346. };
  74347. // Create texture adder post-process
  74348. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74349. var _this = this;
  74350. 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);
  74351. this.textureAdderPostProcess.onApply = function (effect) {
  74352. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74353. effect.setTexture("lensSampler", _this.lensTexture);
  74354. effect.setFloat("exposure", _this.exposure);
  74355. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74356. };
  74357. // Add to pipeline
  74358. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74359. };
  74360. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74361. var _this = this;
  74362. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74363. geometryRenderer.enablePosition = true;
  74364. var geometry = geometryRenderer.getGBuffer();
  74365. // Base post-process
  74366. 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));
  74367. var depthValues = BABYLON.Vector2.Zero();
  74368. this.volumetricLightPostProcess.onApply = function (effect) {
  74369. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74370. var generator = _this.sourceLight.getShadowGenerator();
  74371. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74372. effect.setTexture("positionSampler", geometry.textures[2]);
  74373. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74374. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74375. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74376. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74377. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74378. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74379. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74380. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74381. effect.setVector2("depthValues", depthValues);
  74382. }
  74383. };
  74384. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74385. // Smooth
  74386. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74387. // Merge
  74388. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74389. this.volumetricLightMergePostProces.onApply = function (effect) {
  74390. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74391. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74392. };
  74393. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74394. };
  74395. // Create luminance
  74396. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74397. var _this = this;
  74398. // Create luminance
  74399. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74400. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74401. var offsets = [];
  74402. this.luminancePostProcess.onApply = function (effect) {
  74403. var sU = (1.0 / _this.luminancePostProcess.width);
  74404. var sV = (1.0 / _this.luminancePostProcess.height);
  74405. offsets[0] = -0.5 * sU;
  74406. offsets[1] = 0.5 * sV;
  74407. offsets[2] = 0.5 * sU;
  74408. offsets[3] = 0.5 * sV;
  74409. offsets[4] = -0.5 * sU;
  74410. offsets[5] = -0.5 * sV;
  74411. offsets[6] = 0.5 * sU;
  74412. offsets[7] = -0.5 * sV;
  74413. effect.setArray2("lumOffsets", offsets);
  74414. };
  74415. // Add to pipeline
  74416. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74417. // Create down sample luminance
  74418. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74419. var size = Math.pow(3, i);
  74420. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74421. if (i === 0) {
  74422. defines += "#define FINAL_DOWN_SAMPLER";
  74423. }
  74424. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74425. this.luminanceDownSamplePostProcesses.push(postProcess);
  74426. }
  74427. // Create callbacks and add effects
  74428. var lastLuminance = this.luminancePostProcess;
  74429. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74430. var downSampleOffsets = new Array(18);
  74431. pp.onApply = function (effect) {
  74432. if (!lastLuminance) {
  74433. return;
  74434. }
  74435. var id = 0;
  74436. for (var x = -1; x < 2; x++) {
  74437. for (var y = -1; y < 2; y++) {
  74438. downSampleOffsets[id] = x / lastLuminance.width;
  74439. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74440. id += 2;
  74441. }
  74442. }
  74443. effect.setArray2("dsOffsets", downSampleOffsets);
  74444. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74445. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74446. lastLuminance = _this.luminancePostProcess;
  74447. }
  74448. else {
  74449. lastLuminance = pp;
  74450. }
  74451. };
  74452. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74453. pp.onAfterRender = function (effect) {
  74454. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74455. 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);
  74456. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74457. };
  74458. }
  74459. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74460. });
  74461. };
  74462. // Create HDR post-process
  74463. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74464. var _this = this;
  74465. 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);
  74466. var outputLiminance = 1;
  74467. var time = 0;
  74468. var lastTime = 0;
  74469. this.hdrPostProcess.onApply = function (effect) {
  74470. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74471. time += scene.getEngine().getDeltaTime();
  74472. if (outputLiminance < 0) {
  74473. outputLiminance = _this._hdrCurrentLuminance;
  74474. }
  74475. else {
  74476. var dt = (lastTime - time) / 1000.0;
  74477. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74478. outputLiminance += _this.hdrDecreaseRate * dt;
  74479. }
  74480. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74481. outputLiminance -= _this.hdrIncreaseRate * dt;
  74482. }
  74483. else {
  74484. outputLiminance = _this._hdrCurrentLuminance;
  74485. }
  74486. }
  74487. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74488. effect.setFloat("averageLuminance", outputLiminance);
  74489. lastTime = time;
  74490. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74491. };
  74492. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74493. };
  74494. // Create lens flare post-process
  74495. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74496. var _this = this;
  74497. 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);
  74498. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74499. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74500. 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);
  74501. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74502. var resolution = new BABYLON.Vector2(0, 0);
  74503. // Lens flare
  74504. this.lensFlarePostProcess.onApply = function (effect) {
  74505. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74506. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74507. effect.setFloat("strength", _this.lensFlareStrength);
  74508. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74509. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74510. // Shift
  74511. resolution.x = _this.lensFlarePostProcess.width;
  74512. resolution.y = _this.lensFlarePostProcess.height;
  74513. effect.setVector2("resolution", resolution);
  74514. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74515. };
  74516. // Compose
  74517. 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);
  74518. 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);
  74519. this.lensFlareComposePostProcess.onApply = function (effect) {
  74520. if (!_this._scene.activeCamera) {
  74521. return;
  74522. }
  74523. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74524. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74525. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74526. // Lens start rotation matrix
  74527. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74528. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74529. 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));
  74530. camRot *= 4.0;
  74531. 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);
  74532. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74533. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74534. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74535. };
  74536. };
  74537. // Create depth-of-field post-process
  74538. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74539. var _this = this;
  74540. 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);
  74541. this.depthOfFieldPostProcess.onApply = function (effect) {
  74542. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74543. effect.setTexture("depthSampler", _this._getDepthTexture());
  74544. effect.setFloat("distance", _this.depthOfFieldDistance);
  74545. };
  74546. // Add to pipeline
  74547. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74548. };
  74549. // Create motion blur post-process
  74550. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74551. var _this = this;
  74552. 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);
  74553. var motionScale = 0;
  74554. var prevViewProjection = BABYLON.Matrix.Identity();
  74555. var invViewProjection = BABYLON.Matrix.Identity();
  74556. var viewProjection = BABYLON.Matrix.Identity();
  74557. var screenSize = BABYLON.Vector2.Zero();
  74558. this.motionBlurPostProcess.onApply = function (effect) {
  74559. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74560. viewProjection.invertToRef(invViewProjection);
  74561. effect.setMatrix("inverseViewProjection", invViewProjection);
  74562. effect.setMatrix("prevViewProjection", prevViewProjection);
  74563. prevViewProjection = viewProjection;
  74564. screenSize.x = _this.motionBlurPostProcess.width;
  74565. screenSize.y = _this.motionBlurPostProcess.height;
  74566. effect.setVector2("screenSize", screenSize);
  74567. motionScale = scene.getEngine().getFps() / 60.0;
  74568. effect.setFloat("motionScale", motionScale);
  74569. effect.setFloat("motionStrength", _this.motionStrength);
  74570. effect.setTexture("depthSampler", _this._getDepthTexture());
  74571. };
  74572. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74573. };
  74574. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74575. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74576. var renderer = this._scene.enableGeometryBufferRenderer();
  74577. return renderer.getGBuffer().textures[0];
  74578. }
  74579. return this._scene.enableDepthRenderer().getDepthMap();
  74580. };
  74581. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74582. for (var i = 0; i < this._cameras.length; i++) {
  74583. var camera = this._cameras[i];
  74584. if (this.originalPostProcess) {
  74585. this.originalPostProcess.dispose(camera);
  74586. }
  74587. if (this.downSampleX4PostProcess) {
  74588. this.downSampleX4PostProcess.dispose(camera);
  74589. }
  74590. if (this.brightPassPostProcess) {
  74591. this.brightPassPostProcess.dispose(camera);
  74592. }
  74593. if (this.textureAdderPostProcess) {
  74594. this.textureAdderPostProcess.dispose(camera);
  74595. }
  74596. if (this.textureAdderFinalPostProcess) {
  74597. this.textureAdderFinalPostProcess.dispose(camera);
  74598. }
  74599. if (this.volumetricLightPostProcess) {
  74600. this.volumetricLightPostProcess.dispose(camera);
  74601. }
  74602. if (this.volumetricLightSmoothXPostProcess) {
  74603. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74604. }
  74605. if (this.volumetricLightSmoothYPostProcess) {
  74606. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74607. }
  74608. if (this.volumetricLightMergePostProces) {
  74609. this.volumetricLightMergePostProces.dispose(camera);
  74610. }
  74611. if (this.volumetricLightFinalPostProcess) {
  74612. this.volumetricLightFinalPostProcess.dispose(camera);
  74613. }
  74614. if (this.lensFlarePostProcess) {
  74615. this.lensFlarePostProcess.dispose(camera);
  74616. }
  74617. if (this.lensFlareComposePostProcess) {
  74618. this.lensFlareComposePostProcess.dispose(camera);
  74619. }
  74620. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74621. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74622. }
  74623. if (this.luminancePostProcess) {
  74624. this.luminancePostProcess.dispose(camera);
  74625. }
  74626. if (this.hdrPostProcess) {
  74627. this.hdrPostProcess.dispose(camera);
  74628. }
  74629. if (this.hdrFinalPostProcess) {
  74630. this.hdrFinalPostProcess.dispose(camera);
  74631. }
  74632. if (this.depthOfFieldPostProcess) {
  74633. this.depthOfFieldPostProcess.dispose(camera);
  74634. }
  74635. if (this.motionBlurPostProcess) {
  74636. this.motionBlurPostProcess.dispose(camera);
  74637. }
  74638. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74639. this.blurHPostProcesses[j].dispose(camera);
  74640. }
  74641. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74642. this.blurVPostProcesses[j].dispose(camera);
  74643. }
  74644. }
  74645. this.originalPostProcess = null;
  74646. this.downSampleX4PostProcess = null;
  74647. this.brightPassPostProcess = null;
  74648. this.textureAdderPostProcess = null;
  74649. this.textureAdderFinalPostProcess = null;
  74650. this.volumetricLightPostProcess = null;
  74651. this.volumetricLightSmoothXPostProcess = null;
  74652. this.volumetricLightSmoothYPostProcess = null;
  74653. this.volumetricLightMergePostProces = null;
  74654. this.volumetricLightFinalPostProcess = null;
  74655. this.lensFlarePostProcess = null;
  74656. this.lensFlareComposePostProcess = null;
  74657. this.luminancePostProcess = null;
  74658. this.hdrPostProcess = null;
  74659. this.hdrFinalPostProcess = null;
  74660. this.depthOfFieldPostProcess = null;
  74661. this.motionBlurPostProcess = null;
  74662. this.luminanceDownSamplePostProcesses = [];
  74663. this.blurHPostProcesses = [];
  74664. this.blurVPostProcesses = [];
  74665. };
  74666. /**
  74667. * Dispose of the pipeline and stop all post processes
  74668. */
  74669. StandardRenderingPipeline.prototype.dispose = function () {
  74670. this._disposePostProcesses();
  74671. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74672. _super.prototype.dispose.call(this);
  74673. };
  74674. /**
  74675. * Serialize the rendering pipeline (Used when exporting)
  74676. * @returns the serialized object
  74677. */
  74678. StandardRenderingPipeline.prototype.serialize = function () {
  74679. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74680. if (this.sourceLight) {
  74681. serializationObject.sourceLightId = this.sourceLight.id;
  74682. }
  74683. serializationObject.customType = "StandardRenderingPipeline";
  74684. return serializationObject;
  74685. };
  74686. /**
  74687. * Parse the serialized pipeline
  74688. * @param source Source pipeline.
  74689. * @param scene The scene to load the pipeline to.
  74690. * @param rootUrl The URL of the serialized pipeline.
  74691. * @returns An instantiated pipeline from the serialized object.
  74692. */
  74693. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74694. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74695. if (source.sourceLightId) {
  74696. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74697. }
  74698. return p;
  74699. };
  74700. // Luminance steps
  74701. StandardRenderingPipeline.LuminanceSteps = 6;
  74702. __decorate([
  74703. BABYLON.serialize()
  74704. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74705. __decorate([
  74706. BABYLON.serialize()
  74707. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74708. __decorate([
  74709. BABYLON.serialize()
  74710. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74711. __decorate([
  74712. BABYLON.serialize()
  74713. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74714. __decorate([
  74715. BABYLON.serializeAsTexture("lensTexture")
  74716. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74717. __decorate([
  74718. BABYLON.serialize()
  74719. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74720. __decorate([
  74721. BABYLON.serialize()
  74722. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74723. __decorate([
  74724. BABYLON.serialize()
  74725. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74726. __decorate([
  74727. BABYLON.serialize()
  74728. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74729. __decorate([
  74730. BABYLON.serialize()
  74731. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74732. __decorate([
  74733. BABYLON.serialize()
  74734. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74735. __decorate([
  74736. BABYLON.serializeAsTexture("lensColorTexture")
  74737. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74738. __decorate([
  74739. BABYLON.serialize()
  74740. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74741. __decorate([
  74742. BABYLON.serialize()
  74743. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74744. __decorate([
  74745. BABYLON.serialize()
  74746. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74747. __decorate([
  74748. BABYLON.serialize()
  74749. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74750. __decorate([
  74751. BABYLON.serializeAsTexture("lensStarTexture")
  74752. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74753. __decorate([
  74754. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74755. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74756. __decorate([
  74757. BABYLON.serialize()
  74758. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74759. __decorate([
  74760. BABYLON.serialize()
  74761. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74762. __decorate([
  74763. BABYLON.serialize()
  74764. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74765. __decorate([
  74766. BABYLON.serialize()
  74767. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74768. __decorate([
  74769. BABYLON.serialize()
  74770. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74771. __decorate([
  74772. BABYLON.serialize()
  74773. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74774. __decorate([
  74775. BABYLON.serialize()
  74776. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74777. __decorate([
  74778. BABYLON.serialize()
  74779. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74780. __decorate([
  74781. BABYLON.serialize()
  74782. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74783. __decorate([
  74784. BABYLON.serialize()
  74785. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74786. __decorate([
  74787. BABYLON.serialize()
  74788. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74789. __decorate([
  74790. BABYLON.serialize()
  74791. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74792. return StandardRenderingPipeline;
  74793. }(BABYLON.PostProcessRenderPipeline));
  74794. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74795. })(BABYLON || (BABYLON = {}));
  74796. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74797. var BABYLON;
  74798. (function (BABYLON) {
  74799. var FxaaPostProcess = /** @class */ (function (_super) {
  74800. __extends(FxaaPostProcess, _super);
  74801. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74802. if (camera === void 0) { camera = null; }
  74803. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74804. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74805. var defines = _this._getDefines();
  74806. _this.updateEffect(defines);
  74807. _this.onApplyObservable.add(function (effect) {
  74808. var texelSize = _this.texelSize;
  74809. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74810. });
  74811. return _this;
  74812. }
  74813. FxaaPostProcess.prototype._getDefines = function () {
  74814. var engine = this.getEngine();
  74815. if (!engine) {
  74816. return null;
  74817. }
  74818. var glInfo = engine.getGlInfo();
  74819. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74820. return "#define MALI 1\n";
  74821. }
  74822. return null;
  74823. };
  74824. return FxaaPostProcess;
  74825. }(BABYLON.PostProcess));
  74826. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74827. })(BABYLON || (BABYLON = {}));
  74828. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74829. var BABYLON;
  74830. (function (BABYLON) {
  74831. /**
  74832. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74833. */
  74834. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74835. __extends(ChromaticAberrationPostProcess, _super);
  74836. /**
  74837. * Creates a new instance ChromaticAberrationPostProcess
  74838. * @param name The name of the effect.
  74839. * @param screenWidth The width of the screen to apply the effect on.
  74840. * @param screenHeight The height of the screen to apply the effect on.
  74841. * @param options The required width/height ratio to downsize to before computing the render pass.
  74842. * @param camera The camera to apply the render pass to.
  74843. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74844. * @param engine The engine which the post process will be applied. (default: current engine)
  74845. * @param reusable If the post process can be reused on the same frame. (default: false)
  74846. * @param textureType Type of textures used when performing the post process. (default: 0)
  74847. * @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)
  74848. */
  74849. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74850. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74851. if (blockCompilation === void 0) { blockCompilation = false; }
  74852. 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;
  74853. /**
  74854. * The amount of seperation of rgb channels (default: 30)
  74855. */
  74856. _this.aberrationAmount = 30;
  74857. /**
  74858. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74859. */
  74860. _this.radialIntensity = 0;
  74861. /**
  74862. * 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))
  74863. */
  74864. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74865. /**
  74866. * 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))
  74867. */
  74868. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74869. _this.onApplyObservable.add(function (effect) {
  74870. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74871. effect.setFloat('screen_width', screenWidth);
  74872. effect.setFloat('screen_height', screenHeight);
  74873. effect.setFloat('radialIntensity', _this.radialIntensity);
  74874. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74875. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74876. });
  74877. return _this;
  74878. }
  74879. return ChromaticAberrationPostProcess;
  74880. }(BABYLON.PostProcess));
  74881. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74882. })(BABYLON || (BABYLON = {}));
  74883. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74884. var BABYLON;
  74885. (function (BABYLON) {
  74886. /**
  74887. * The GrainPostProcess adds noise to the image at mid luminance levels
  74888. */
  74889. var GrainPostProcess = /** @class */ (function (_super) {
  74890. __extends(GrainPostProcess, _super);
  74891. /**
  74892. * Creates a new instance of @see GrainPostProcess
  74893. * @param name The name of the effect.
  74894. * @param options The required width/height ratio to downsize to before computing the render pass.
  74895. * @param camera The camera to apply the render pass to.
  74896. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74897. * @param engine The engine which the post process will be applied. (default: current engine)
  74898. * @param reusable If the post process can be reused on the same frame. (default: false)
  74899. * @param textureType Type of textures used when performing the post process. (default: 0)
  74900. * @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)
  74901. */
  74902. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74903. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74904. if (blockCompilation === void 0) { blockCompilation = false; }
  74905. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74906. /**
  74907. * The intensity of the grain added (default: 30)
  74908. */
  74909. _this.intensity = 30;
  74910. /**
  74911. * If the grain should be randomized on every frame
  74912. */
  74913. _this.animated = false;
  74914. _this.onApplyObservable.add(function (effect) {
  74915. effect.setFloat('intensity', _this.intensity);
  74916. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74917. });
  74918. return _this;
  74919. }
  74920. return GrainPostProcess;
  74921. }(BABYLON.PostProcess));
  74922. BABYLON.GrainPostProcess = GrainPostProcess;
  74923. })(BABYLON || (BABYLON = {}));
  74924. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74925. var BABYLON;
  74926. (function (BABYLON) {
  74927. /**
  74928. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74929. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74930. */
  74931. var SharpenPostProcess = /** @class */ (function (_super) {
  74932. __extends(SharpenPostProcess, _super);
  74933. /**
  74934. * Creates a new instance ConvolutionPostProcess
  74935. * @param name The name of the effect.
  74936. * @param options The required width/height ratio to downsize to before computing the render pass.
  74937. * @param camera The camera to apply the render pass to.
  74938. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74939. * @param engine The engine which the post process will be applied. (default: current engine)
  74940. * @param reusable If the post process can be reused on the same frame. (default: false)
  74941. * @param textureType Type of textures used when performing the post process. (default: 0)
  74942. * @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)
  74943. */
  74944. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74945. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74946. if (blockCompilation === void 0) { blockCompilation = false; }
  74947. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74948. /**
  74949. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74950. */
  74951. _this.colorAmount = 1.0;
  74952. /**
  74953. * How much sharpness should be applied (default: 0.3)
  74954. */
  74955. _this.edgeAmount = 0.3;
  74956. _this.onApply = function (effect) {
  74957. effect.setFloat2("screenSize", _this.width, _this.height);
  74958. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74959. };
  74960. return _this;
  74961. }
  74962. return SharpenPostProcess;
  74963. }(BABYLON.PostProcess));
  74964. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74965. })(BABYLON || (BABYLON = {}));
  74966. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74967. var BABYLON;
  74968. (function (BABYLON) {
  74969. /**
  74970. * The Blur Post Process which blurs an image based on a kernel and direction.
  74971. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74972. */
  74973. var BlurPostProcess = /** @class */ (function (_super) {
  74974. __extends(BlurPostProcess, _super);
  74975. /**
  74976. * Creates a new instance BlurPostProcess
  74977. * @param name The name of the effect.
  74978. * @param direction The direction in which to blur the image.
  74979. * @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.
  74980. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74981. * @param camera The camera to apply the render pass to.
  74982. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74983. * @param engine The engine which the post process will be applied. (default: current engine)
  74984. * @param reusable If the post process can be reused on the same frame. (default: false)
  74985. * @param textureType Type of textures used when performing the post process. (default: 0)
  74986. * @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)
  74987. */
  74988. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74989. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74990. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74991. if (defines === void 0) { defines = ""; }
  74992. if (blockCompilation === void 0) { blockCompilation = false; }
  74993. 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;
  74994. _this.direction = direction;
  74995. _this.blockCompilation = blockCompilation;
  74996. _this._packedFloat = false;
  74997. _this._staticDefines = "";
  74998. _this._staticDefines = defines;
  74999. _this.onApplyObservable.add(function (effect) {
  75000. if (_this._outputTexture) {
  75001. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75002. }
  75003. else {
  75004. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75005. }
  75006. });
  75007. _this.kernel = kernel;
  75008. return _this;
  75009. }
  75010. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75011. /**
  75012. * Gets the length in pixels of the blur sample region
  75013. */
  75014. get: function () {
  75015. return this._idealKernel;
  75016. },
  75017. /**
  75018. * Sets the length in pixels of the blur sample region
  75019. */
  75020. set: function (v) {
  75021. if (this._idealKernel === v) {
  75022. return;
  75023. }
  75024. v = Math.max(v, 1);
  75025. this._idealKernel = v;
  75026. this._kernel = this._nearestBestKernel(v);
  75027. if (!this.blockCompilation) {
  75028. this._updateParameters();
  75029. }
  75030. },
  75031. enumerable: true,
  75032. configurable: true
  75033. });
  75034. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75035. /**
  75036. * Gets wether or not the blur is unpacking/repacking floats
  75037. */
  75038. get: function () {
  75039. return this._packedFloat;
  75040. },
  75041. /**
  75042. * Sets wether or not the blur needs to unpack/repack floats
  75043. */
  75044. set: function (v) {
  75045. if (this._packedFloat === v) {
  75046. return;
  75047. }
  75048. this._packedFloat = v;
  75049. if (!this.blockCompilation) {
  75050. this._updateParameters();
  75051. }
  75052. },
  75053. enumerable: true,
  75054. configurable: true
  75055. });
  75056. /**
  75057. * Updates the effect with the current post process compile time values and recompiles the shader.
  75058. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75059. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75060. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75061. * @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
  75062. * @param onCompiled Called when the shader has been compiled.
  75063. * @param onError Called if there is an error when compiling a shader.
  75064. */
  75065. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75066. if (defines === void 0) { defines = null; }
  75067. if (uniforms === void 0) { uniforms = null; }
  75068. if (samplers === void 0) { samplers = null; }
  75069. this._updateParameters(onCompiled, onError);
  75070. };
  75071. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75072. // Generate sampling offsets and weights
  75073. var N = this._kernel;
  75074. var centerIndex = (N - 1) / 2;
  75075. // Generate Gaussian sampling weights over kernel
  75076. var offsets = [];
  75077. var weights = [];
  75078. var totalWeight = 0;
  75079. for (var i = 0; i < N; i++) {
  75080. var u = i / (N - 1);
  75081. var w = this._gaussianWeight(u * 2.0 - 1);
  75082. offsets[i] = (i - centerIndex);
  75083. weights[i] = w;
  75084. totalWeight += w;
  75085. }
  75086. // Normalize weights
  75087. for (var i = 0; i < weights.length; i++) {
  75088. weights[i] /= totalWeight;
  75089. }
  75090. // Optimize: combine samples to take advantage of hardware linear sampling
  75091. // Walk from left to center, combining pairs (symmetrically)
  75092. var linearSamplingWeights = [];
  75093. var linearSamplingOffsets = [];
  75094. var linearSamplingMap = [];
  75095. for (var i = 0; i <= centerIndex; i += 2) {
  75096. var j = Math.min(i + 1, Math.floor(centerIndex));
  75097. var singleCenterSample = i === j;
  75098. if (singleCenterSample) {
  75099. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75100. }
  75101. else {
  75102. var sharedCell = j === centerIndex;
  75103. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75104. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75105. if (offsetLinear === 0) {
  75106. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75107. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75108. }
  75109. else {
  75110. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75111. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75112. }
  75113. }
  75114. }
  75115. for (var i = 0; i < linearSamplingMap.length; i++) {
  75116. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75117. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75118. }
  75119. // Replace with optimized
  75120. offsets = linearSamplingOffsets;
  75121. weights = linearSamplingWeights;
  75122. // Generate shaders
  75123. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75124. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75125. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75126. var defines = "";
  75127. defines += this._staticDefines;
  75128. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75129. if (this._staticDefines.indexOf("DOF") != -1) {
  75130. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75131. varyingCount--;
  75132. }
  75133. for (var i = 0; i < varyingCount; i++) {
  75134. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75135. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75136. }
  75137. var depCount = 0;
  75138. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75139. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75140. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75141. depCount++;
  75142. }
  75143. if (this.packedFloat) {
  75144. defines += "#define PACKEDFLOAT 1";
  75145. }
  75146. this.blockCompilation = false;
  75147. _super.prototype.updateEffect.call(this, defines, null, null, {
  75148. varyingCount: varyingCount,
  75149. depCount: depCount
  75150. }, onCompiled, onError);
  75151. };
  75152. /**
  75153. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75154. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75155. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75156. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75157. * The gaps between physical kernels are compensated for in the weighting of the samples
  75158. * @param idealKernel Ideal blur kernel.
  75159. * @return Nearest best kernel.
  75160. */
  75161. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75162. var v = Math.round(idealKernel);
  75163. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75164. var k = _a[_i];
  75165. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75166. return Math.max(k, 3);
  75167. }
  75168. }
  75169. return Math.max(v, 3);
  75170. };
  75171. /**
  75172. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75173. * @param x The point on the Gaussian distribution to sample.
  75174. * @return the value of the Gaussian function at x.
  75175. */
  75176. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75177. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75178. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75179. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75180. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75181. // truncated at around 1.3% of peak strength.
  75182. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75183. var sigma = (1 / 3);
  75184. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75185. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75186. var weight = (1.0 / denominator) * Math.exp(exponent);
  75187. return weight;
  75188. };
  75189. /**
  75190. * Generates a string that can be used as a floating point number in GLSL.
  75191. * @param x Value to print.
  75192. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75193. * @return GLSL float string.
  75194. */
  75195. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75196. if (decimalFigures === void 0) { decimalFigures = 8; }
  75197. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75198. };
  75199. return BlurPostProcess;
  75200. }(BABYLON.PostProcess));
  75201. BABYLON.BlurPostProcess = BlurPostProcess;
  75202. })(BABYLON || (BABYLON = {}));
  75203. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75204. var BABYLON;
  75205. (function (BABYLON) {
  75206. /**
  75207. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75208. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75209. * based on samples that have a large difference in distance than the center pixel.
  75210. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75211. */
  75212. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75213. __extends(DepthOfFieldBlurPostProcess, _super);
  75214. /**
  75215. * Creates a new instance CircleOfConfusionPostProcess
  75216. * @param name The name of the effect.
  75217. * @param scene The scene the effect belongs to.
  75218. * @param direction The direction the blur should be applied.
  75219. * @param kernel The size of the kernel used to blur.
  75220. * @param options The required width/height ratio to downsize to before computing the render pass.
  75221. * @param camera The camera to apply the render pass to.
  75222. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75223. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75224. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75225. * @param engine The engine which the post process will be applied. (default: current engine)
  75226. * @param reusable If the post process can be reused on the same frame. (default: false)
  75227. * @param textureType Type of textures used when performing the post process. (default: 0)
  75228. * @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)
  75229. */
  75230. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75231. if (imageToBlur === void 0) { imageToBlur = null; }
  75232. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75233. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75234. if (blockCompilation === void 0) { blockCompilation = false; }
  75235. 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;
  75236. _this.direction = direction;
  75237. _this.onApplyObservable.add(function (effect) {
  75238. if (imageToBlur != null) {
  75239. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75240. }
  75241. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75242. if (scene.activeCamera) {
  75243. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75244. }
  75245. });
  75246. return _this;
  75247. }
  75248. return DepthOfFieldBlurPostProcess;
  75249. }(BABYLON.BlurPostProcess));
  75250. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75251. })(BABYLON || (BABYLON = {}));
  75252. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75253. var BABYLON;
  75254. (function (BABYLON) {
  75255. /**
  75256. * Options to be set when merging outputs from the default pipeline.
  75257. */
  75258. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75259. function DepthOfFieldMergePostProcessOptions() {
  75260. }
  75261. return DepthOfFieldMergePostProcessOptions;
  75262. }());
  75263. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75264. /**
  75265. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75266. */
  75267. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75268. __extends(DepthOfFieldMergePostProcess, _super);
  75269. /**
  75270. * Creates a new instance of DepthOfFieldMergePostProcess
  75271. * @param name The name of the effect.
  75272. * @param originalFromInput Post process which's input will be used for the merge.
  75273. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75274. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75275. * @param options The required width/height ratio to downsize to before computing the render pass.
  75276. * @param camera The camera to apply the render pass to.
  75277. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75278. * @param engine The engine which the post process will be applied. (default: current engine)
  75279. * @param reusable If the post process can be reused on the same frame. (default: false)
  75280. * @param textureType Type of textures used when performing the post process. (default: 0)
  75281. * @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)
  75282. */
  75283. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75284. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75285. if (blockCompilation === void 0) { blockCompilation = false; }
  75286. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75287. _this.blurSteps = blurSteps;
  75288. _this.onApplyObservable.add(function (effect) {
  75289. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75290. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75291. blurSteps.forEach(function (step, index) {
  75292. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75293. });
  75294. });
  75295. if (!blockCompilation) {
  75296. _this.updateEffect();
  75297. }
  75298. return _this;
  75299. }
  75300. /**
  75301. * Updates the effect with the current post process compile time values and recompiles the shader.
  75302. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75303. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75304. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75305. * @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
  75306. * @param onCompiled Called when the shader has been compiled.
  75307. * @param onError Called if there is an error when compiling a shader.
  75308. */
  75309. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75310. if (defines === void 0) { defines = null; }
  75311. if (uniforms === void 0) { uniforms = null; }
  75312. if (samplers === void 0) { samplers = null; }
  75313. if (!defines) {
  75314. defines = "";
  75315. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75316. }
  75317. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75318. };
  75319. return DepthOfFieldMergePostProcess;
  75320. }(BABYLON.PostProcess));
  75321. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75322. })(BABYLON || (BABYLON = {}));
  75323. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75324. var BABYLON;
  75325. (function (BABYLON) {
  75326. /**
  75327. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75328. */
  75329. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75330. __extends(CircleOfConfusionPostProcess, _super);
  75331. /**
  75332. * Creates a new instance CircleOfConfusionPostProcess
  75333. * @param name The name of the effect.
  75334. * @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.
  75335. * @param options The required width/height ratio to downsize to before computing the render pass.
  75336. * @param camera The camera to apply the render pass to.
  75337. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75338. * @param engine The engine which the post process will be applied. (default: current engine)
  75339. * @param reusable If the post process can be reused on the same frame. (default: false)
  75340. * @param textureType Type of textures used when performing the post process. (default: 0)
  75341. * @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)
  75342. */
  75343. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75344. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75345. if (blockCompilation === void 0) { blockCompilation = false; }
  75346. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75347. /**
  75348. * 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.
  75349. */
  75350. _this.lensSize = 50;
  75351. /**
  75352. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75353. */
  75354. _this.fStop = 1.4;
  75355. /**
  75356. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75357. */
  75358. _this.focusDistance = 2000;
  75359. /**
  75360. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75361. */
  75362. _this.focalLength = 50;
  75363. _this._depthTexture = null;
  75364. _this._depthTexture = depthTexture;
  75365. _this.onApplyObservable.add(function (effect) {
  75366. if (!_this._depthTexture) {
  75367. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75368. return;
  75369. }
  75370. effect.setTexture("depthSampler", _this._depthTexture);
  75371. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75372. var aperture = _this.lensSize / _this.fStop;
  75373. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75374. effect.setFloat('focusDistance', _this.focusDistance);
  75375. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75376. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75377. });
  75378. return _this;
  75379. }
  75380. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75381. /**
  75382. * 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.
  75383. */
  75384. set: function (value) {
  75385. this._depthTexture = value;
  75386. },
  75387. enumerable: true,
  75388. configurable: true
  75389. });
  75390. return CircleOfConfusionPostProcess;
  75391. }(BABYLON.PostProcess));
  75392. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75393. })(BABYLON || (BABYLON = {}));
  75394. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75395. var BABYLON;
  75396. (function (BABYLON) {
  75397. /**
  75398. * Specifies the level of max blur that should be applied when using the depth of field effect
  75399. */
  75400. var DepthOfFieldEffectBlurLevel;
  75401. (function (DepthOfFieldEffectBlurLevel) {
  75402. /**
  75403. * Subtle blur
  75404. */
  75405. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75406. /**
  75407. * Medium blur
  75408. */
  75409. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75410. /**
  75411. * Large blur
  75412. */
  75413. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75414. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75415. ;
  75416. /**
  75417. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75418. */
  75419. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75420. __extends(DepthOfFieldEffect, _super);
  75421. /**
  75422. * Creates a new instance DepthOfFieldEffect
  75423. * @param scene The scene the effect belongs to.
  75424. * @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.
  75425. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75426. * @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)
  75427. */
  75428. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75429. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75430. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75431. if (blockCompilation === void 0) { blockCompilation = false; }
  75432. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75433. return _this._effects;
  75434. }, true) || this;
  75435. /**
  75436. * Internal post processes in depth of field effect
  75437. */
  75438. _this._effects = [];
  75439. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75440. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75441. // 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)
  75442. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75443. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75444. _this._depthOfFieldBlurY = [];
  75445. _this._depthOfFieldBlurX = [];
  75446. var blurCount = 1;
  75447. var kernelSize = 15;
  75448. switch (blurLevel) {
  75449. case DepthOfFieldEffectBlurLevel.High: {
  75450. blurCount = 3;
  75451. kernelSize = 51;
  75452. break;
  75453. }
  75454. case DepthOfFieldEffectBlurLevel.Medium: {
  75455. blurCount = 2;
  75456. kernelSize = 31;
  75457. break;
  75458. }
  75459. default: {
  75460. kernelSize = 15;
  75461. blurCount = 1;
  75462. break;
  75463. }
  75464. }
  75465. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75466. var ratio = 1.0;
  75467. for (var i = 0; i < blurCount; i++) {
  75468. 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);
  75469. blurY.autoClear = false;
  75470. ratio = 0.75 / Math.pow(2, i);
  75471. 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);
  75472. blurX.autoClear = false;
  75473. _this._depthOfFieldBlurY.push(blurY);
  75474. _this._depthOfFieldBlurX.push(blurX);
  75475. }
  75476. // Set all post processes on the effect.
  75477. _this._effects = [_this._circleOfConfusion];
  75478. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75479. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75480. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75481. }
  75482. // Merge blurred images with original image based on circleOfConfusion
  75483. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75484. _this._dofMerge.autoClear = false;
  75485. _this._effects.push(_this._dofMerge);
  75486. return _this;
  75487. }
  75488. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75489. get: function () {
  75490. return this._circleOfConfusion.focalLength;
  75491. },
  75492. /**
  75493. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75494. */
  75495. set: function (value) {
  75496. this._circleOfConfusion.focalLength = value;
  75497. },
  75498. enumerable: true,
  75499. configurable: true
  75500. });
  75501. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75502. get: function () {
  75503. return this._circleOfConfusion.fStop;
  75504. },
  75505. /**
  75506. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75507. */
  75508. set: function (value) {
  75509. this._circleOfConfusion.fStop = value;
  75510. },
  75511. enumerable: true,
  75512. configurable: true
  75513. });
  75514. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75515. get: function () {
  75516. return this._circleOfConfusion.focusDistance;
  75517. },
  75518. /**
  75519. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75520. */
  75521. set: function (value) {
  75522. this._circleOfConfusion.focusDistance = value;
  75523. },
  75524. enumerable: true,
  75525. configurable: true
  75526. });
  75527. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75528. get: function () {
  75529. return this._circleOfConfusion.lensSize;
  75530. },
  75531. /**
  75532. * 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.
  75533. */
  75534. set: function (value) {
  75535. this._circleOfConfusion.lensSize = value;
  75536. },
  75537. enumerable: true,
  75538. configurable: true
  75539. });
  75540. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75541. /**
  75542. * 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.
  75543. */
  75544. set: function (value) {
  75545. this._circleOfConfusion.depthTexture = value;
  75546. },
  75547. enumerable: true,
  75548. configurable: true
  75549. });
  75550. /**
  75551. * Disposes each of the internal effects for a given camera.
  75552. * @param camera The camera to dispose the effect on.
  75553. */
  75554. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75555. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75556. this._effects[effectIndex].dispose(camera);
  75557. }
  75558. };
  75559. /**
  75560. * Internal
  75561. */
  75562. DepthOfFieldEffect.prototype._updateEffects = function () {
  75563. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75564. this._effects[effectIndex].updateEffect();
  75565. }
  75566. };
  75567. /**
  75568. * Internal
  75569. * @returns if all the contained post processes are ready.
  75570. */
  75571. DepthOfFieldEffect.prototype._isReady = function () {
  75572. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75573. if (!this._effects[effectIndex].isReady()) {
  75574. return false;
  75575. }
  75576. }
  75577. return true;
  75578. };
  75579. return DepthOfFieldEffect;
  75580. }(BABYLON.PostProcessRenderEffect));
  75581. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75582. })(BABYLON || (BABYLON = {}));
  75583. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75584. var BABYLON;
  75585. (function (BABYLON) {
  75586. /**
  75587. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75588. */
  75589. var BloomMergePostProcess = /** @class */ (function (_super) {
  75590. __extends(BloomMergePostProcess, _super);
  75591. /**
  75592. * Creates a new instance of @see BloomMergePostProcess
  75593. * @param name The name of the effect.
  75594. * @param originalFromInput Post process which's input will be used for the merge.
  75595. * @param blurred Blurred highlights post process which's output will be used.
  75596. * @param weight Weight of the bloom to be added to the original input.
  75597. * @param options The required width/height ratio to downsize to before computing the render pass.
  75598. * @param camera The camera to apply the render pass to.
  75599. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75600. * @param engine The engine which the post process will be applied. (default: current engine)
  75601. * @param reusable If the post process can be reused on the same frame. (default: false)
  75602. * @param textureType Type of textures used when performing the post process. (default: 0)
  75603. * @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)
  75604. */
  75605. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75606. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75607. if (blockCompilation === void 0) { blockCompilation = false; }
  75608. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75609. _this.weight = weight;
  75610. _this.onApplyObservable.add(function (effect) {
  75611. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75612. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75613. effect.setFloat("bloomWeight", _this.weight);
  75614. });
  75615. if (!blockCompilation) {
  75616. _this.updateEffect();
  75617. }
  75618. return _this;
  75619. }
  75620. return BloomMergePostProcess;
  75621. }(BABYLON.PostProcess));
  75622. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75623. })(BABYLON || (BABYLON = {}));
  75624. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75625. var BABYLON;
  75626. (function (BABYLON) {
  75627. /**
  75628. * 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.
  75629. */
  75630. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75631. __extends(ExtractHighlightsPostProcess, _super);
  75632. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75633. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75634. if (blockCompilation === void 0) { blockCompilation = false; }
  75635. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75636. /**
  75637. * The luminance threshold, pixels below this value will be set to black.
  75638. */
  75639. _this.threshold = 0.9;
  75640. /**
  75641. * Internal
  75642. */
  75643. _this._exposure = 1;
  75644. /**
  75645. * Post process which has the input texture to be used when performing highlight extraction
  75646. */
  75647. _this._inputPostProcess = null;
  75648. _this.onApplyObservable.add(function (effect) {
  75649. if (_this._inputPostProcess) {
  75650. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75651. }
  75652. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75653. effect.setFloat('exposure', _this._exposure);
  75654. });
  75655. return _this;
  75656. }
  75657. return ExtractHighlightsPostProcess;
  75658. }(BABYLON.PostProcess));
  75659. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75660. })(BABYLON || (BABYLON = {}));
  75661. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75662. var BABYLON;
  75663. (function (BABYLON) {
  75664. /**
  75665. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75666. */
  75667. var BloomEffect = /** @class */ (function (_super) {
  75668. __extends(BloomEffect, _super);
  75669. /**
  75670. * Creates a new instance of @see BloomEffect
  75671. * @param scene The scene the effect belongs to.
  75672. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75673. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75674. * @param bloomWeight The the strength of bloom.
  75675. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75676. * @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)
  75677. */
  75678. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75679. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75680. if (blockCompilation === void 0) { blockCompilation = false; }
  75681. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75682. return _this._effects;
  75683. }, true) || this;
  75684. _this.bloomScale = bloomScale;
  75685. /**
  75686. * Internal
  75687. */
  75688. _this._effects = [];
  75689. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75690. _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);
  75691. _this._blurX.alwaysForcePOT = true;
  75692. _this._blurX.autoClear = false;
  75693. _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);
  75694. _this._blurY.alwaysForcePOT = true;
  75695. _this._blurY.autoClear = false;
  75696. _this.kernel = bloomKernel;
  75697. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75698. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75699. _this._merge.autoClear = false;
  75700. _this._effects.push(_this._merge);
  75701. return _this;
  75702. }
  75703. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75704. /**
  75705. * The luminance threshold to find bright areas of the image to bloom.
  75706. */
  75707. get: function () {
  75708. return this._downscale.threshold;
  75709. },
  75710. set: function (value) {
  75711. this._downscale.threshold = value;
  75712. },
  75713. enumerable: true,
  75714. configurable: true
  75715. });
  75716. Object.defineProperty(BloomEffect.prototype, "weight", {
  75717. /**
  75718. * The strength of the bloom.
  75719. */
  75720. get: function () {
  75721. return this._merge.weight;
  75722. },
  75723. set: function (value) {
  75724. this._merge.weight = value;
  75725. },
  75726. enumerable: true,
  75727. configurable: true
  75728. });
  75729. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75730. /**
  75731. * Specifies the size of the bloom blur kernel, relative to the final output size
  75732. */
  75733. get: function () {
  75734. return this._blurX.kernel / this.bloomScale;
  75735. },
  75736. set: function (value) {
  75737. this._blurX.kernel = value * this.bloomScale;
  75738. this._blurY.kernel = value * this.bloomScale;
  75739. },
  75740. enumerable: true,
  75741. configurable: true
  75742. });
  75743. /**
  75744. * Disposes each of the internal effects for a given camera.
  75745. * @param camera The camera to dispose the effect on.
  75746. */
  75747. BloomEffect.prototype.disposeEffects = function (camera) {
  75748. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75749. this._effects[effectIndex].dispose(camera);
  75750. }
  75751. };
  75752. /**
  75753. * Internal
  75754. */
  75755. BloomEffect.prototype._updateEffects = function () {
  75756. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75757. this._effects[effectIndex].updateEffect();
  75758. }
  75759. };
  75760. /**
  75761. * Internal
  75762. * @returns if all the contained post processes are ready.
  75763. */
  75764. BloomEffect.prototype._isReady = function () {
  75765. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75766. if (!this._effects[effectIndex].isReady()) {
  75767. return false;
  75768. }
  75769. }
  75770. return true;
  75771. };
  75772. return BloomEffect;
  75773. }(BABYLON.PostProcessRenderEffect));
  75774. BABYLON.BloomEffect = BloomEffect;
  75775. })(BABYLON || (BABYLON = {}));
  75776. //# sourceMappingURL=babylon.bloomEffect.js.map
  75777. var BABYLON;
  75778. (function (BABYLON) {
  75779. /**
  75780. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75781. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75782. */
  75783. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75784. __extends(DefaultRenderingPipeline, _super);
  75785. /**
  75786. * @constructor
  75787. * @param {string} name - The rendering pipeline name (default: "")
  75788. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  75789. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  75790. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  75791. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  75792. */
  75793. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75794. if (name === void 0) { name = ""; }
  75795. if (hdr === void 0) { hdr = true; }
  75796. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75797. if (automaticBuild === void 0) { automaticBuild = true; }
  75798. var _this = _super.call(this, scene.getEngine(), name) || this;
  75799. _this._originalCameras = [];
  75800. /**
  75801. * ID of the sharpen post process,
  75802. */
  75803. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75804. /**
  75805. * ID of the image processing post process;
  75806. */
  75807. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75808. /**
  75809. * ID of the Fast Approximate Anti-Aliasing post process;
  75810. */
  75811. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75812. /**
  75813. * ID of the chromatic aberration post process,
  75814. */
  75815. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75816. /**
  75817. * ID of the grain post process
  75818. */
  75819. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75820. /**
  75821. * Glow post process which adds a glow to emmisive areas of the image
  75822. */
  75823. _this._glowLayer = null;
  75824. /**
  75825. * Animations which can be used to tweak settings over a period of time
  75826. */
  75827. _this.animations = [];
  75828. _this._imageProcessingConfigurationObserver = null;
  75829. // Values
  75830. _this._sharpenEnabled = false;
  75831. _this._bloomEnabled = false;
  75832. _this._depthOfFieldEnabled = false;
  75833. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75834. _this._fxaaEnabled = false;
  75835. _this._imageProcessingEnabled = true;
  75836. _this._bloomScale = 0.5;
  75837. _this._chromaticAberrationEnabled = false;
  75838. _this._grainEnabled = false;
  75839. _this._buildAllowed = true;
  75840. _this._resizeObserver = null;
  75841. _this._hardwareScaleLevel = 1.0;
  75842. _this._bloomKernel = 64;
  75843. /**
  75844. * Specifies the weight of the bloom in the final rendering
  75845. */
  75846. _this._bloomWeight = 0.15;
  75847. /**
  75848. * Specifies the luma threshold for the area that will be blurred by the bloom
  75849. */
  75850. _this._bloomThreshold = 0.9;
  75851. _this._samples = 1;
  75852. _this._hasCleared = false;
  75853. _this._prevPostProcess = null;
  75854. _this._prevPrevPostProcess = null;
  75855. _this._cameras = cameras || scene.cameras;
  75856. _this._originalCameras = _this._cameras.slice();
  75857. _this._buildAllowed = automaticBuild;
  75858. // Initialize
  75859. _this._scene = scene;
  75860. var caps = _this._scene.getEngine().getCaps();
  75861. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75862. // Misc
  75863. if (_this._hdr) {
  75864. if (caps.textureHalfFloatRender) {
  75865. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75866. }
  75867. else if (caps.textureFloatRender) {
  75868. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75869. }
  75870. }
  75871. else {
  75872. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75873. }
  75874. // Attach
  75875. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75876. var engine = _this._scene.getEngine();
  75877. // Create post processes before hand so they can be modified before enabled.
  75878. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75879. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75880. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75881. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75882. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75883. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75884. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75885. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75886. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75887. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75888. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75889. _this.bloomKernel = _this.bloomKernel;
  75890. });
  75891. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75892. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75893. });
  75894. _this._buildPipeline();
  75895. return _this;
  75896. }
  75897. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75898. get: function () {
  75899. return this._sharpenEnabled;
  75900. },
  75901. /**
  75902. * Enable or disable the sharpen process from the pipeline
  75903. */
  75904. set: function (enabled) {
  75905. if (this._sharpenEnabled === enabled) {
  75906. return;
  75907. }
  75908. this._sharpenEnabled = enabled;
  75909. this._buildPipeline();
  75910. },
  75911. enumerable: true,
  75912. configurable: true
  75913. });
  75914. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75915. /**
  75916. * Specifies the size of the bloom blur kernel, relative to the final output size
  75917. */
  75918. get: function () {
  75919. return this._bloomKernel;
  75920. },
  75921. set: function (value) {
  75922. this._bloomKernel = value;
  75923. this.bloom.kernel = value / this._hardwareScaleLevel;
  75924. },
  75925. enumerable: true,
  75926. configurable: true
  75927. });
  75928. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75929. get: function () {
  75930. return this._bloomWeight;
  75931. },
  75932. /**
  75933. * The strength of the bloom.
  75934. */
  75935. set: function (value) {
  75936. if (this._bloomWeight === value) {
  75937. return;
  75938. }
  75939. this.bloom.weight = value;
  75940. this._bloomWeight = value;
  75941. },
  75942. enumerable: true,
  75943. configurable: true
  75944. });
  75945. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75946. get: function () {
  75947. return this._bloomThreshold;
  75948. },
  75949. /**
  75950. * The strength of the bloom.
  75951. */
  75952. set: function (value) {
  75953. if (this._bloomThreshold === value) {
  75954. return;
  75955. }
  75956. this.bloom.threshold = value;
  75957. this._bloomThreshold = value;
  75958. },
  75959. enumerable: true,
  75960. configurable: true
  75961. });
  75962. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75963. get: function () {
  75964. return this._bloomScale;
  75965. },
  75966. /**
  75967. * The scale of the bloom, lower value will provide better performance.
  75968. */
  75969. set: function (value) {
  75970. if (this._bloomScale === value) {
  75971. return;
  75972. }
  75973. this._bloomScale = value;
  75974. // recreate bloom and dispose old as this setting is not dynamic
  75975. this._rebuildBloom();
  75976. this._buildPipeline();
  75977. },
  75978. enumerable: true,
  75979. configurable: true
  75980. });
  75981. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75982. get: function () {
  75983. return this._bloomEnabled;
  75984. },
  75985. /**
  75986. * Enable or disable the bloom from the pipeline
  75987. */
  75988. set: function (enabled) {
  75989. if (this._bloomEnabled === enabled) {
  75990. return;
  75991. }
  75992. this._bloomEnabled = enabled;
  75993. this._buildPipeline();
  75994. },
  75995. enumerable: true,
  75996. configurable: true
  75997. });
  75998. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75999. // recreate bloom and dispose old as this setting is not dynamic
  76000. var oldBloom = this.bloom;
  76001. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76002. this.bloom.threshold = oldBloom.threshold;
  76003. for (var i = 0; i < this._cameras.length; i++) {
  76004. oldBloom.disposeEffects(this._cameras[i]);
  76005. }
  76006. };
  76007. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76008. /**
  76009. * If the depth of field is enabled.
  76010. */
  76011. get: function () {
  76012. return this._depthOfFieldEnabled;
  76013. },
  76014. set: function (enabled) {
  76015. if (this._depthOfFieldEnabled === enabled) {
  76016. return;
  76017. }
  76018. this._depthOfFieldEnabled = enabled;
  76019. this._buildPipeline();
  76020. },
  76021. enumerable: true,
  76022. configurable: true
  76023. });
  76024. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76025. /**
  76026. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76027. */
  76028. get: function () {
  76029. return this._depthOfFieldBlurLevel;
  76030. },
  76031. set: function (value) {
  76032. if (this._depthOfFieldBlurLevel === value) {
  76033. return;
  76034. }
  76035. this._depthOfFieldBlurLevel = value;
  76036. // recreate dof and dispose old as this setting is not dynamic
  76037. var oldDof = this.depthOfField;
  76038. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76039. this.depthOfField.focalLength = oldDof.focalLength;
  76040. this.depthOfField.focusDistance = oldDof.focusDistance;
  76041. this.depthOfField.fStop = oldDof.fStop;
  76042. this.depthOfField.lensSize = oldDof.lensSize;
  76043. for (var i = 0; i < this._cameras.length; i++) {
  76044. oldDof.disposeEffects(this._cameras[i]);
  76045. }
  76046. this._buildPipeline();
  76047. },
  76048. enumerable: true,
  76049. configurable: true
  76050. });
  76051. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76052. get: function () {
  76053. return this._fxaaEnabled;
  76054. },
  76055. /**
  76056. * If the anti aliasing is enabled.
  76057. */
  76058. set: function (enabled) {
  76059. if (this._fxaaEnabled === enabled) {
  76060. return;
  76061. }
  76062. this._fxaaEnabled = enabled;
  76063. this._buildPipeline();
  76064. },
  76065. enumerable: true,
  76066. configurable: true
  76067. });
  76068. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76069. get: function () {
  76070. return this._samples;
  76071. },
  76072. /**
  76073. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76074. */
  76075. set: function (sampleCount) {
  76076. if (this._samples === sampleCount) {
  76077. return;
  76078. }
  76079. this._samples = sampleCount;
  76080. this._buildPipeline();
  76081. },
  76082. enumerable: true,
  76083. configurable: true
  76084. });
  76085. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76086. get: function () {
  76087. return this._imageProcessingEnabled;
  76088. },
  76089. /**
  76090. * If image processing is enabled.
  76091. */
  76092. set: function (enabled) {
  76093. if (this._imageProcessingEnabled === enabled) {
  76094. return;
  76095. }
  76096. this._imageProcessingEnabled = enabled;
  76097. this._buildPipeline();
  76098. },
  76099. enumerable: true,
  76100. configurable: true
  76101. });
  76102. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76103. get: function () {
  76104. return this._glowLayer == null;
  76105. },
  76106. /**
  76107. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76108. */
  76109. set: function (enabled) {
  76110. if (enabled && !this._glowLayer) {
  76111. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76112. }
  76113. else if (!enabled && this._glowLayer) {
  76114. this._glowLayer.dispose();
  76115. this._glowLayer = null;
  76116. }
  76117. },
  76118. enumerable: true,
  76119. configurable: true
  76120. });
  76121. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76122. get: function () {
  76123. return this._chromaticAberrationEnabled;
  76124. },
  76125. /**
  76126. * Enable or disable the chromaticAberration process from the pipeline
  76127. */
  76128. set: function (enabled) {
  76129. if (this._chromaticAberrationEnabled === enabled) {
  76130. return;
  76131. }
  76132. this._chromaticAberrationEnabled = enabled;
  76133. this._buildPipeline();
  76134. },
  76135. enumerable: true,
  76136. configurable: true
  76137. });
  76138. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76139. get: function () {
  76140. return this._grainEnabled;
  76141. },
  76142. /**
  76143. * Enable or disable the grain process from the pipeline
  76144. */
  76145. set: function (enabled) {
  76146. if (this._grainEnabled === enabled) {
  76147. return;
  76148. }
  76149. this._grainEnabled = enabled;
  76150. this._buildPipeline();
  76151. },
  76152. enumerable: true,
  76153. configurable: true
  76154. });
  76155. /**
  76156. * Force the compilation of the entire pipeline.
  76157. */
  76158. DefaultRenderingPipeline.prototype.prepare = function () {
  76159. var previousState = this._buildAllowed;
  76160. this._buildAllowed = true;
  76161. this._buildPipeline();
  76162. this._buildAllowed = previousState;
  76163. };
  76164. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76165. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76166. if (this._hasCleared) {
  76167. postProcess.autoClear = false;
  76168. }
  76169. else {
  76170. postProcess.autoClear = true;
  76171. this._scene.autoClear = false;
  76172. this._hasCleared = true;
  76173. }
  76174. if (!skipTextureSharing) {
  76175. if (this._prevPrevPostProcess) {
  76176. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76177. }
  76178. else {
  76179. postProcess.useOwnOutput();
  76180. }
  76181. if (this._prevPostProcess) {
  76182. this._prevPrevPostProcess = this._prevPostProcess;
  76183. }
  76184. this._prevPostProcess = postProcess;
  76185. }
  76186. };
  76187. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76188. var _this = this;
  76189. if (!this._buildAllowed) {
  76190. return;
  76191. }
  76192. this._scene.autoClear = true;
  76193. var engine = this._scene.getEngine();
  76194. this._disposePostProcesses();
  76195. if (this._cameras !== null) {
  76196. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76197. // get back cameras to be used to reattach pipeline
  76198. this._cameras = this._originalCameras.slice();
  76199. }
  76200. this._reset();
  76201. this._prevPostProcess = null;
  76202. this._prevPrevPostProcess = null;
  76203. this._hasCleared = false;
  76204. if (this.depthOfFieldEnabled) {
  76205. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76206. this.depthOfField.depthTexture = depthTexture;
  76207. if (!this.depthOfField._isReady()) {
  76208. this.depthOfField._updateEffects();
  76209. }
  76210. this.addEffect(this.depthOfField);
  76211. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76212. }
  76213. if (this.bloomEnabled) {
  76214. if (!this.bloom._isReady()) {
  76215. this.bloom._updateEffects();
  76216. }
  76217. this.addEffect(this.bloom);
  76218. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76219. }
  76220. if (this._imageProcessingEnabled) {
  76221. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76222. if (this._hdr) {
  76223. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76224. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76225. }
  76226. else {
  76227. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76228. }
  76229. }
  76230. if (this.sharpenEnabled) {
  76231. if (!this.sharpen.isReady()) {
  76232. this.sharpen.updateEffect();
  76233. }
  76234. this.addEffect(this._sharpenEffect);
  76235. this._setAutoClearAndTextureSharing(this.sharpen);
  76236. }
  76237. if (this.grainEnabled) {
  76238. if (!this.grain.isReady()) {
  76239. this.grain.updateEffect();
  76240. }
  76241. this.addEffect(this._grainEffect);
  76242. this._setAutoClearAndTextureSharing(this.grain);
  76243. }
  76244. if (this.chromaticAberrationEnabled) {
  76245. if (!this.chromaticAberration.isReady()) {
  76246. this.chromaticAberration.updateEffect();
  76247. }
  76248. this.addEffect(this._chromaticAberrationEffect);
  76249. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76250. }
  76251. if (this.fxaaEnabled) {
  76252. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76253. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76254. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76255. }
  76256. if (this._cameras !== null) {
  76257. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76258. }
  76259. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76260. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76261. }
  76262. };
  76263. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76264. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76265. for (var i = 0; i < this._cameras.length; i++) {
  76266. var camera = this._cameras[i];
  76267. if (this.imageProcessing) {
  76268. this.imageProcessing.dispose(camera);
  76269. }
  76270. if (this.fxaa) {
  76271. this.fxaa.dispose(camera);
  76272. }
  76273. // These are created in the constructor and should not be disposed on every pipeline change
  76274. if (disposeNonRecreated) {
  76275. if (this.sharpen) {
  76276. this.sharpen.dispose(camera);
  76277. }
  76278. if (this.depthOfField) {
  76279. this.depthOfField.disposeEffects(camera);
  76280. }
  76281. if (this.bloom) {
  76282. this.bloom.disposeEffects(camera);
  76283. }
  76284. if (this.chromaticAberration) {
  76285. this.chromaticAberration.dispose(camera);
  76286. }
  76287. if (this.grain) {
  76288. this.grain.dispose(camera);
  76289. }
  76290. if (this._glowLayer) {
  76291. this._glowLayer.dispose();
  76292. }
  76293. }
  76294. }
  76295. this.imageProcessing = null;
  76296. this.fxaa = null;
  76297. if (disposeNonRecreated) {
  76298. this.sharpen = null;
  76299. this._sharpenEffect = null;
  76300. this.depthOfField = null;
  76301. this.bloom = null;
  76302. this.chromaticAberration = null;
  76303. this._chromaticAberrationEffect = null;
  76304. this.grain = null;
  76305. this._grainEffect = null;
  76306. this._glowLayer = null;
  76307. }
  76308. };
  76309. /**
  76310. * Dispose of the pipeline and stop all post processes
  76311. */
  76312. DefaultRenderingPipeline.prototype.dispose = function () {
  76313. this._disposePostProcesses(true);
  76314. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76315. this._scene.autoClear = true;
  76316. if (this._resizeObserver) {
  76317. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76318. this._resizeObserver = null;
  76319. }
  76320. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76321. _super.prototype.dispose.call(this);
  76322. };
  76323. /**
  76324. * Serialize the rendering pipeline (Used when exporting)
  76325. * @returns the serialized object
  76326. */
  76327. DefaultRenderingPipeline.prototype.serialize = function () {
  76328. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76329. serializationObject.customType = "DefaultRenderingPipeline";
  76330. return serializationObject;
  76331. };
  76332. /**
  76333. * Parse the serialized pipeline
  76334. * @param source Source pipeline.
  76335. * @param scene The scene to load the pipeline to.
  76336. * @param rootUrl The URL of the serialized pipeline.
  76337. * @returns An instantiated pipeline from the serialized object.
  76338. */
  76339. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76340. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76341. };
  76342. __decorate([
  76343. BABYLON.serialize()
  76344. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76345. __decorate([
  76346. BABYLON.serialize()
  76347. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76348. __decorate([
  76349. BABYLON.serialize()
  76350. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76351. __decorate([
  76352. BABYLON.serialize()
  76353. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76354. __decorate([
  76355. BABYLON.serialize()
  76356. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76357. __decorate([
  76358. BABYLON.serialize()
  76359. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76360. __decorate([
  76361. BABYLON.serialize()
  76362. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76363. __decorate([
  76364. BABYLON.serialize()
  76365. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76366. __decorate([
  76367. BABYLON.serialize()
  76368. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76369. __decorate([
  76370. BABYLON.serialize()
  76371. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76372. __decorate([
  76373. BABYLON.serialize()
  76374. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76375. __decorate([
  76376. BABYLON.serialize()
  76377. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76378. __decorate([
  76379. BABYLON.serialize()
  76380. ], DefaultRenderingPipeline.prototype, "samples", null);
  76381. __decorate([
  76382. BABYLON.serialize()
  76383. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76384. __decorate([
  76385. BABYLON.serialize()
  76386. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76387. __decorate([
  76388. BABYLON.serialize()
  76389. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76390. __decorate([
  76391. BABYLON.serialize()
  76392. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76393. return DefaultRenderingPipeline;
  76394. }(BABYLON.PostProcessRenderPipeline));
  76395. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76396. })(BABYLON || (BABYLON = {}));
  76397. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76398. var BABYLON;
  76399. (function (BABYLON) {
  76400. /**
  76401. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76402. */
  76403. var GeometryBufferRenderer = /** @class */ (function () {
  76404. /**
  76405. * Creates a new G Buffer for the scene
  76406. * @param scene The scene the buffer belongs to
  76407. * @param ratio How big is the buffer related to the main canvas.
  76408. */
  76409. function GeometryBufferRenderer(scene, ratio) {
  76410. if (ratio === void 0) { ratio = 1; }
  76411. this._enablePosition = false;
  76412. this._scene = scene;
  76413. this._ratio = ratio;
  76414. // Render target
  76415. this._createRenderTargets();
  76416. }
  76417. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76418. /**
  76419. * Set the render list (meshes to be rendered) used in the G buffer.
  76420. */
  76421. set: function (meshes) {
  76422. this._multiRenderTarget.renderList = meshes;
  76423. },
  76424. enumerable: true,
  76425. configurable: true
  76426. });
  76427. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76428. /**
  76429. * Gets wether or not G buffer are supported by the running hardware.
  76430. * This requires draw buffer supports
  76431. */
  76432. get: function () {
  76433. return this._multiRenderTarget.isSupported;
  76434. },
  76435. enumerable: true,
  76436. configurable: true
  76437. });
  76438. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76439. /**
  76440. * Gets wether or not position are enabled for the G buffer.
  76441. */
  76442. get: function () {
  76443. return this._enablePosition;
  76444. },
  76445. /**
  76446. * Sets wether or not position are enabled for the G buffer.
  76447. */
  76448. set: function (enable) {
  76449. this._enablePosition = enable;
  76450. this.dispose();
  76451. this._createRenderTargets();
  76452. },
  76453. enumerable: true,
  76454. configurable: true
  76455. });
  76456. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76457. /**
  76458. * Gets the scene associated with the buffer.
  76459. */
  76460. get: function () {
  76461. return this._scene;
  76462. },
  76463. enumerable: true,
  76464. configurable: true
  76465. });
  76466. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76467. /**
  76468. * Gets the ratio used by the buffer during its creation.
  76469. * How big is the buffer related to the main canvas.
  76470. */
  76471. get: function () {
  76472. return this._ratio;
  76473. },
  76474. enumerable: true,
  76475. configurable: true
  76476. });
  76477. /**
  76478. * Checks wether everything is ready to render a submesh to the G buffer.
  76479. * @param subMesh the submesh to check readiness for
  76480. * @param useInstances is the mesh drawn using instance or not
  76481. * @returns true if ready otherwise false
  76482. */
  76483. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76484. var material = subMesh.getMaterial();
  76485. if (material && material.disableDepthWrite) {
  76486. return false;
  76487. }
  76488. var defines = [];
  76489. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76490. var mesh = subMesh.getMesh();
  76491. // Alpha test
  76492. if (material && material.needAlphaTesting()) {
  76493. defines.push("#define ALPHATEST");
  76494. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76495. attribs.push(BABYLON.VertexBuffer.UVKind);
  76496. defines.push("#define UV1");
  76497. }
  76498. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76499. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76500. defines.push("#define UV2");
  76501. }
  76502. }
  76503. // Buffers
  76504. if (this._enablePosition) {
  76505. defines.push("#define POSITION");
  76506. }
  76507. // Bones
  76508. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76509. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76510. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76511. if (mesh.numBoneInfluencers > 4) {
  76512. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76513. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76514. }
  76515. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76516. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76517. }
  76518. else {
  76519. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76520. }
  76521. // Instances
  76522. if (useInstances) {
  76523. defines.push("#define INSTANCES");
  76524. attribs.push("world0");
  76525. attribs.push("world1");
  76526. attribs.push("world2");
  76527. attribs.push("world3");
  76528. }
  76529. // Get correct effect
  76530. var join = defines.join("\n");
  76531. if (this._cachedDefines !== join) {
  76532. this._cachedDefines = join;
  76533. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76534. }
  76535. return this._effect.isReady();
  76536. };
  76537. /**
  76538. * Gets the current underlying G Buffer.
  76539. * @returns the buffer
  76540. */
  76541. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76542. return this._multiRenderTarget;
  76543. };
  76544. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76545. /**
  76546. * Gets the number of samples used to render the buffer (anti aliasing).
  76547. */
  76548. get: function () {
  76549. return this._multiRenderTarget.samples;
  76550. },
  76551. /**
  76552. * Sets the number of samples used to render the buffer (anti aliasing).
  76553. */
  76554. set: function (value) {
  76555. this._multiRenderTarget.samples = value;
  76556. },
  76557. enumerable: true,
  76558. configurable: true
  76559. });
  76560. /**
  76561. * Disposes the renderer and frees up associated resources.
  76562. */
  76563. GeometryBufferRenderer.prototype.dispose = function () {
  76564. this.getGBuffer().dispose();
  76565. };
  76566. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76567. var _this = this;
  76568. var engine = this._scene.getEngine();
  76569. var count = this._enablePosition ? 3 : 2;
  76570. 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 });
  76571. if (!this.isSupported) {
  76572. return;
  76573. }
  76574. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76575. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76576. this._multiRenderTarget.refreshRate = 1;
  76577. this._multiRenderTarget.renderParticles = false;
  76578. this._multiRenderTarget.renderList = null;
  76579. // set default depth value to 1.0 (far away)
  76580. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76581. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76582. });
  76583. // Custom render function
  76584. var renderSubMesh = function (subMesh) {
  76585. var mesh = subMesh.getRenderingMesh();
  76586. var scene = _this._scene;
  76587. var engine = scene.getEngine();
  76588. var material = subMesh.getMaterial();
  76589. if (!material) {
  76590. return;
  76591. }
  76592. // Culling
  76593. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76594. // Managing instances
  76595. var batch = mesh._getInstancesRenderList(subMesh._id);
  76596. if (batch.mustReturn) {
  76597. return;
  76598. }
  76599. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76600. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76601. engine.enableEffect(_this._effect);
  76602. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76603. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76604. _this._effect.setMatrix("view", scene.getViewMatrix());
  76605. // Alpha test
  76606. if (material && material.needAlphaTesting()) {
  76607. var alphaTexture = material.getAlphaTestTexture();
  76608. if (alphaTexture) {
  76609. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76610. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76611. }
  76612. }
  76613. // Bones
  76614. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76615. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76616. }
  76617. // Draw
  76618. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76619. }
  76620. };
  76621. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76622. var index;
  76623. if (depthOnlySubMeshes.length) {
  76624. engine.setColorWrite(false);
  76625. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76626. renderSubMesh(depthOnlySubMeshes.data[index]);
  76627. }
  76628. engine.setColorWrite(true);
  76629. }
  76630. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76631. renderSubMesh(opaqueSubMeshes.data[index]);
  76632. }
  76633. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76634. renderSubMesh(alphaTestSubMeshes.data[index]);
  76635. }
  76636. };
  76637. };
  76638. return GeometryBufferRenderer;
  76639. }());
  76640. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76641. })(BABYLON || (BABYLON = {}));
  76642. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76643. var BABYLON;
  76644. (function (BABYLON) {
  76645. /**
  76646. * This groups together the common properties used for image processing either in direct forward pass
  76647. * or through post processing effect depending on the use of the image processing pipeline in your scene
  76648. * or not.
  76649. */
  76650. var ImageProcessingConfiguration = /** @class */ (function () {
  76651. function ImageProcessingConfiguration() {
  76652. /**
  76653. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  76654. */
  76655. this.colorCurves = new BABYLON.ColorCurves();
  76656. this._colorCurvesEnabled = false;
  76657. this._colorGradingEnabled = false;
  76658. this._colorGradingWithGreenDepth = true;
  76659. this._colorGradingBGR = true;
  76660. this._exposure = 1.0;
  76661. this._toneMappingEnabled = false;
  76662. this._contrast = 1.0;
  76663. /**
  76664. * Vignette stretch size.
  76665. */
  76666. this.vignetteStretch = 0;
  76667. /**
  76668. * Vignette centre X Offset.
  76669. */
  76670. this.vignetteCentreX = 0;
  76671. /**
  76672. * Vignette centre Y Offset.
  76673. */
  76674. this.vignetteCentreY = 0;
  76675. /**
  76676. * Vignette weight or intensity of the vignette effect.
  76677. */
  76678. this.vignetteWeight = 1.5;
  76679. /**
  76680. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  76681. * if vignetteEnabled is set to true.
  76682. */
  76683. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  76684. /**
  76685. * Camera field of view used by the Vignette effect.
  76686. */
  76687. this.vignetteCameraFov = 0.5;
  76688. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  76689. this._vignetteEnabled = false;
  76690. this._applyByPostProcess = false;
  76691. this._isEnabled = true;
  76692. /**
  76693. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  76694. */
  76695. this.onUpdateParameters = new BABYLON.Observable();
  76696. }
  76697. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  76698. /**
  76699. * Gets wether the color curves effect is enabled.
  76700. */
  76701. get: function () {
  76702. return this._colorCurvesEnabled;
  76703. },
  76704. /**
  76705. * Sets wether the color curves effect is enabled.
  76706. */
  76707. set: function (value) {
  76708. if (this._colorCurvesEnabled === value) {
  76709. return;
  76710. }
  76711. this._colorCurvesEnabled = value;
  76712. this._updateParameters();
  76713. },
  76714. enumerable: true,
  76715. configurable: true
  76716. });
  76717. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  76718. /**
  76719. * Gets wether the color grading effect is enabled.
  76720. */
  76721. get: function () {
  76722. return this._colorGradingEnabled;
  76723. },
  76724. /**
  76725. * Sets wether the color grading effect is enabled.
  76726. */
  76727. set: function (value) {
  76728. if (this._colorGradingEnabled === value) {
  76729. return;
  76730. }
  76731. this._colorGradingEnabled = value;
  76732. this._updateParameters();
  76733. },
  76734. enumerable: true,
  76735. configurable: true
  76736. });
  76737. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  76738. /**
  76739. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  76740. */
  76741. get: function () {
  76742. return this._colorGradingWithGreenDepth;
  76743. },
  76744. /**
  76745. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  76746. */
  76747. set: function (value) {
  76748. if (this._colorGradingWithGreenDepth === value) {
  76749. return;
  76750. }
  76751. this._colorGradingWithGreenDepth = value;
  76752. this._updateParameters();
  76753. },
  76754. enumerable: true,
  76755. configurable: true
  76756. });
  76757. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  76758. /**
  76759. * Gets wether the color grading texture contains BGR values.
  76760. */
  76761. get: function () {
  76762. return this._colorGradingBGR;
  76763. },
  76764. /**
  76765. * Sets wether the color grading texture contains BGR values.
  76766. */
  76767. set: function (value) {
  76768. if (this._colorGradingBGR === value) {
  76769. return;
  76770. }
  76771. this._colorGradingBGR = value;
  76772. this._updateParameters();
  76773. },
  76774. enumerable: true,
  76775. configurable: true
  76776. });
  76777. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  76778. /**
  76779. * Gets the Exposure used in the effect.
  76780. */
  76781. get: function () {
  76782. return this._exposure;
  76783. },
  76784. /**
  76785. * Sets the Exposure used in the effect.
  76786. */
  76787. set: function (value) {
  76788. if (this._exposure === value) {
  76789. return;
  76790. }
  76791. this._exposure = value;
  76792. this._updateParameters();
  76793. },
  76794. enumerable: true,
  76795. configurable: true
  76796. });
  76797. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  76798. /**
  76799. * Gets wether the tone mapping effect is enabled.
  76800. */
  76801. get: function () {
  76802. return this._toneMappingEnabled;
  76803. },
  76804. /**
  76805. * Sets wether the tone mapping effect is enabled.
  76806. */
  76807. set: function (value) {
  76808. if (this._toneMappingEnabled === value) {
  76809. return;
  76810. }
  76811. this._toneMappingEnabled = value;
  76812. this._updateParameters();
  76813. },
  76814. enumerable: true,
  76815. configurable: true
  76816. });
  76817. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  76818. /**
  76819. * Gets the contrast used in the effect.
  76820. */
  76821. get: function () {
  76822. return this._contrast;
  76823. },
  76824. /**
  76825. * Sets the contrast used in the effect.
  76826. */
  76827. set: function (value) {
  76828. if (this._contrast === value) {
  76829. return;
  76830. }
  76831. this._contrast = value;
  76832. this._updateParameters();
  76833. },
  76834. enumerable: true,
  76835. configurable: true
  76836. });
  76837. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  76838. /**
  76839. * Gets the vignette blend mode allowing different kind of effect.
  76840. */
  76841. get: function () {
  76842. return this._vignetteBlendMode;
  76843. },
  76844. /**
  76845. * Sets the vignette blend mode allowing different kind of effect.
  76846. */
  76847. set: function (value) {
  76848. if (this._vignetteBlendMode === value) {
  76849. return;
  76850. }
  76851. this._vignetteBlendMode = value;
  76852. this._updateParameters();
  76853. },
  76854. enumerable: true,
  76855. configurable: true
  76856. });
  76857. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  76858. /**
  76859. * Gets wether the vignette effect is enabled.
  76860. */
  76861. get: function () {
  76862. return this._vignetteEnabled;
  76863. },
  76864. /**
  76865. * Sets wether the vignette effect is enabled.
  76866. */
  76867. set: function (value) {
  76868. if (this._vignetteEnabled === value) {
  76869. return;
  76870. }
  76871. this._vignetteEnabled = value;
  76872. this._updateParameters();
  76873. },
  76874. enumerable: true,
  76875. configurable: true
  76876. });
  76877. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  76878. /**
  76879. * Gets wether the image processing is applied through a post process or not.
  76880. */
  76881. get: function () {
  76882. return this._applyByPostProcess;
  76883. },
  76884. /**
  76885. * Sets wether the image processing is applied through a post process or not.
  76886. */
  76887. set: function (value) {
  76888. if (this._applyByPostProcess === value) {
  76889. return;
  76890. }
  76891. this._applyByPostProcess = value;
  76892. this._updateParameters();
  76893. },
  76894. enumerable: true,
  76895. configurable: true
  76896. });
  76897. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  76898. /**
  76899. * Gets wether the image processing is enabled or not.
  76900. */
  76901. get: function () {
  76902. return this._isEnabled;
  76903. },
  76904. /**
  76905. * Sets wether the image processing is enabled or not.
  76906. */
  76907. set: function (value) {
  76908. if (this._isEnabled === value) {
  76909. return;
  76910. }
  76911. this._isEnabled = value;
  76912. this._updateParameters();
  76913. },
  76914. enumerable: true,
  76915. configurable: true
  76916. });
  76917. /**
  76918. * Method called each time the image processing information changes requires to recompile the effect.
  76919. */
  76920. ImageProcessingConfiguration.prototype._updateParameters = function () {
  76921. this.onUpdateParameters.notifyObservers(this);
  76922. };
  76923. ImageProcessingConfiguration.prototype.getClassName = function () {
  76924. return "ImageProcessingConfiguration";
  76925. };
  76926. /**
  76927. * Prepare the list of uniforms associated with the Image Processing effects.
  76928. * @param uniformsList The list of uniforms used in the effect
  76929. * @param defines the list of defines currently in use
  76930. */
  76931. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  76932. if (defines.EXPOSURE) {
  76933. uniforms.push("exposureLinear");
  76934. }
  76935. if (defines.CONTRAST) {
  76936. uniforms.push("contrast");
  76937. }
  76938. if (defines.COLORGRADING) {
  76939. uniforms.push("colorTransformSettings");
  76940. }
  76941. if (defines.VIGNETTE) {
  76942. uniforms.push("vInverseScreenSize");
  76943. uniforms.push("vignetteSettings1");
  76944. uniforms.push("vignetteSettings2");
  76945. }
  76946. if (defines.COLORCURVES) {
  76947. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  76948. }
  76949. };
  76950. /**
  76951. * Prepare the list of samplers associated with the Image Processing effects.
  76952. * @param uniformsList The list of uniforms used in the effect
  76953. * @param defines the list of defines currently in use
  76954. */
  76955. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  76956. if (defines.COLORGRADING) {
  76957. samplersList.push("txColorTransform");
  76958. }
  76959. };
  76960. /**
  76961. * Prepare the list of defines associated to the shader.
  76962. * @param defines the list of defines to complete
  76963. */
  76964. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  76965. if (forPostProcess === void 0) { forPostProcess = false; }
  76966. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  76967. defines.VIGNETTE = false;
  76968. defines.TONEMAPPING = false;
  76969. defines.CONTRAST = false;
  76970. defines.EXPOSURE = false;
  76971. defines.COLORCURVES = false;
  76972. defines.COLORGRADING = false;
  76973. defines.COLORGRADING3D = false;
  76974. defines.IMAGEPROCESSING = false;
  76975. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  76976. return;
  76977. }
  76978. defines.VIGNETTE = this.vignetteEnabled;
  76979. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  76980. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  76981. defines.TONEMAPPING = this.toneMappingEnabled;
  76982. defines.CONTRAST = (this.contrast !== 1.0);
  76983. defines.EXPOSURE = (this.exposure !== 1.0);
  76984. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  76985. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  76986. if (defines.COLORGRADING) {
  76987. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  76988. }
  76989. else {
  76990. defines.COLORGRADING3D = false;
  76991. }
  76992. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  76993. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  76994. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  76995. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  76996. };
  76997. /**
  76998. * Returns true if all the image processing information are ready.
  76999. */
  77000. ImageProcessingConfiguration.prototype.isReady = function () {
  77001. // Color Grading texure can not be none blocking.
  77002. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  77003. };
  77004. /**
  77005. * Binds the image processing to the shader.
  77006. * @param effect The effect to bind to
  77007. */
  77008. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  77009. if (aspectRatio === void 0) { aspectRatio = 1; }
  77010. // Color Curves
  77011. if (this._colorCurvesEnabled && this.colorCurves) {
  77012. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  77013. }
  77014. // Vignette
  77015. if (this._vignetteEnabled) {
  77016. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  77017. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  77018. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  77019. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  77020. var vignetteScaleX = vignetteScaleY * aspectRatio;
  77021. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  77022. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  77023. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  77024. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  77025. var vignettePower = -2.0 * this.vignetteWeight;
  77026. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  77027. }
  77028. // Exposure
  77029. effect.setFloat("exposureLinear", this.exposure);
  77030. // Contrast
  77031. effect.setFloat("contrast", this.contrast);
  77032. // Color transform settings
  77033. if (this.colorGradingTexture) {
  77034. effect.setTexture("txColorTransform", this.colorGradingTexture);
  77035. var textureSize = this.colorGradingTexture.getSize().height;
  77036. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  77037. 0.5 / textureSize, // textureOffset
  77038. textureSize, // textureSize
  77039. this.colorGradingTexture.level // weight
  77040. );
  77041. }
  77042. };
  77043. /**
  77044. * Clones the current image processing instance.
  77045. * @return The cloned image processing
  77046. */
  77047. ImageProcessingConfiguration.prototype.clone = function () {
  77048. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  77049. };
  77050. /**
  77051. * Serializes the current image processing instance to a json representation.
  77052. * @return a JSON representation
  77053. */
  77054. ImageProcessingConfiguration.prototype.serialize = function () {
  77055. return BABYLON.SerializationHelper.Serialize(this);
  77056. };
  77057. /**
  77058. * Parses the image processing from a json representation.
  77059. * @param source the JSON source to parse
  77060. * @return The parsed image processing
  77061. */
  77062. ImageProcessingConfiguration.Parse = function (source) {
  77063. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  77064. };
  77065. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  77066. /**
  77067. * Used to apply the vignette as a mix with the pixel color.
  77068. */
  77069. get: function () {
  77070. return this._VIGNETTEMODE_MULTIPLY;
  77071. },
  77072. enumerable: true,
  77073. configurable: true
  77074. });
  77075. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  77076. /**
  77077. * Used to apply the vignette as a replacement of the pixel color.
  77078. */
  77079. get: function () {
  77080. return this._VIGNETTEMODE_OPAQUE;
  77081. },
  77082. enumerable: true,
  77083. configurable: true
  77084. });
  77085. // Static constants associated to the image processing.
  77086. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  77087. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  77088. __decorate([
  77089. BABYLON.serializeAsColorCurves()
  77090. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  77091. __decorate([
  77092. BABYLON.serialize()
  77093. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  77094. __decorate([
  77095. BABYLON.serializeAsTexture()
  77096. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  77097. __decorate([
  77098. BABYLON.serialize()
  77099. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  77100. __decorate([
  77101. BABYLON.serialize()
  77102. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  77103. __decorate([
  77104. BABYLON.serialize()
  77105. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  77106. __decorate([
  77107. BABYLON.serialize()
  77108. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  77109. __decorate([
  77110. BABYLON.serialize()
  77111. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  77112. __decorate([
  77113. BABYLON.serialize()
  77114. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  77115. __decorate([
  77116. BABYLON.serialize()
  77117. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  77118. __decorate([
  77119. BABYLON.serialize()
  77120. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  77121. __decorate([
  77122. BABYLON.serialize()
  77123. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  77124. __decorate([
  77125. BABYLON.serialize()
  77126. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  77127. __decorate([
  77128. BABYLON.serializeAsColor4()
  77129. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  77130. __decorate([
  77131. BABYLON.serialize()
  77132. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  77133. __decorate([
  77134. BABYLON.serialize()
  77135. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  77136. __decorate([
  77137. BABYLON.serialize()
  77138. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  77139. __decorate([
  77140. BABYLON.serialize()
  77141. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  77142. __decorate([
  77143. BABYLON.serialize()
  77144. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  77145. return ImageProcessingConfiguration;
  77146. }());
  77147. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  77148. })(BABYLON || (BABYLON = {}));
  77149. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  77150. var BABYLON;
  77151. (function (BABYLON) {
  77152. /**
  77153. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  77154. * It can help converting any input color in a desired output one. This can then be used to create effects
  77155. * from sepia, black and white to sixties or futuristic rendering...
  77156. *
  77157. * The only supported format is currently 3dl.
  77158. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  77159. */
  77160. var ColorGradingTexture = /** @class */ (function (_super) {
  77161. __extends(ColorGradingTexture, _super);
  77162. /**
  77163. * Instantiates a ColorGradingTexture from the following parameters.
  77164. *
  77165. * @param url The location of the color gradind data (currently only supporting 3dl)
  77166. * @param scene The scene the texture will be used in
  77167. */
  77168. function ColorGradingTexture(url, scene) {
  77169. var _this = _super.call(this, scene) || this;
  77170. if (!url) {
  77171. return _this;
  77172. }
  77173. _this._engine = scene.getEngine();
  77174. _this._textureMatrix = BABYLON.Matrix.Identity();
  77175. _this.name = url;
  77176. _this.url = url;
  77177. _this.hasAlpha = false;
  77178. _this.isCube = false;
  77179. _this.is3D = _this._engine.webGLVersion > 1;
  77180. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77181. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77182. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77183. _this.anisotropicFilteringLevel = 1;
  77184. _this._texture = _this._getFromCache(url, true);
  77185. if (!_this._texture) {
  77186. if (!scene.useDelayedTextureLoading) {
  77187. _this.loadTexture();
  77188. }
  77189. else {
  77190. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  77191. }
  77192. }
  77193. return _this;
  77194. }
  77195. /**
  77196. * Returns the texture matrix used in most of the material.
  77197. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  77198. */
  77199. ColorGradingTexture.prototype.getTextureMatrix = function () {
  77200. return this._textureMatrix;
  77201. };
  77202. /**
  77203. * Occurs when the file being loaded is a .3dl LUT file.
  77204. */
  77205. ColorGradingTexture.prototype.load3dlTexture = function () {
  77206. var engine = this._engine;
  77207. var texture;
  77208. if (engine.webGLVersion === 1) {
  77209. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77210. }
  77211. else {
  77212. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77213. }
  77214. this._texture = texture;
  77215. var callback = function (text) {
  77216. if (typeof text !== "string") {
  77217. return;
  77218. }
  77219. var data = null;
  77220. var tempData = null;
  77221. var line;
  77222. var lines = text.split('\n');
  77223. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  77224. var maxColor = 0;
  77225. for (var i = 0; i < lines.length; i++) {
  77226. line = lines[i];
  77227. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  77228. continue;
  77229. if (line.indexOf('#') === 0)
  77230. continue;
  77231. var words = line.split(" ");
  77232. if (size === 0) {
  77233. // Number of space + one
  77234. size = words.length;
  77235. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  77236. tempData = new Float32Array(size * size * size * 4);
  77237. continue;
  77238. }
  77239. if (size != 0) {
  77240. var r = Math.max(parseInt(words[0]), 0);
  77241. var g = Math.max(parseInt(words[1]), 0);
  77242. var b = Math.max(parseInt(words[2]), 0);
  77243. maxColor = Math.max(r, maxColor);
  77244. maxColor = Math.max(g, maxColor);
  77245. maxColor = Math.max(b, maxColor);
  77246. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  77247. if (tempData) {
  77248. tempData[pixelStorageIndex + 0] = r;
  77249. tempData[pixelStorageIndex + 1] = g;
  77250. tempData[pixelStorageIndex + 2] = b;
  77251. }
  77252. pixelIndexSlice++;
  77253. if (pixelIndexSlice % size == 0) {
  77254. pixelIndexH++;
  77255. pixelIndexSlice = 0;
  77256. if (pixelIndexH % size == 0) {
  77257. pixelIndexW++;
  77258. pixelIndexH = 0;
  77259. }
  77260. }
  77261. }
  77262. }
  77263. if (tempData && data) {
  77264. for (var i = 0; i < tempData.length; i++) {
  77265. if (i > 0 && (i + 1) % 4 === 0) {
  77266. data[i] = 255;
  77267. }
  77268. else {
  77269. var value = tempData[i];
  77270. data[i] = (value / maxColor * 255);
  77271. }
  77272. }
  77273. }
  77274. if (texture.is3D) {
  77275. texture.updateSize(size, size, size);
  77276. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77277. }
  77278. else {
  77279. texture.updateSize(size * size, size);
  77280. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77281. }
  77282. };
  77283. var scene = this.getScene();
  77284. if (scene) {
  77285. scene._loadFile(this.url, callback);
  77286. }
  77287. else {
  77288. this._engine._loadFile(this.url, callback);
  77289. }
  77290. return this._texture;
  77291. };
  77292. /**
  77293. * Starts the loading process of the texture.
  77294. */
  77295. ColorGradingTexture.prototype.loadTexture = function () {
  77296. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  77297. this.load3dlTexture();
  77298. }
  77299. };
  77300. /**
  77301. * Clones the color gradind texture.
  77302. */
  77303. ColorGradingTexture.prototype.clone = function () {
  77304. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  77305. // Base texture
  77306. newTexture.level = this.level;
  77307. return newTexture;
  77308. };
  77309. /**
  77310. * Called during delayed load for textures.
  77311. */
  77312. ColorGradingTexture.prototype.delayLoad = function () {
  77313. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  77314. return;
  77315. }
  77316. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  77317. this._texture = this._getFromCache(this.url, true);
  77318. if (!this._texture) {
  77319. this.loadTexture();
  77320. }
  77321. };
  77322. /**
  77323. * Parses a color grading texture serialized by Babylon.
  77324. * @param parsedTexture The texture information being parsedTexture
  77325. * @param scene The scene to load the texture in
  77326. * @param rootUrl The root url of the data assets to load
  77327. * @return A color gradind texture
  77328. */
  77329. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  77330. var texture = null;
  77331. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  77332. texture = new ColorGradingTexture(parsedTexture.name, scene);
  77333. texture.name = parsedTexture.name;
  77334. texture.level = parsedTexture.level;
  77335. }
  77336. return texture;
  77337. };
  77338. /**
  77339. * Serializes the LUT texture to json format.
  77340. */
  77341. ColorGradingTexture.prototype.serialize = function () {
  77342. if (!this.name) {
  77343. return null;
  77344. }
  77345. var serializationObject = {};
  77346. serializationObject.name = this.name;
  77347. serializationObject.level = this.level;
  77348. serializationObject.customType = "BABYLON.ColorGradingTexture";
  77349. return serializationObject;
  77350. };
  77351. /**
  77352. * Empty line regex stored for GC.
  77353. */
  77354. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  77355. return ColorGradingTexture;
  77356. }(BABYLON.BaseTexture));
  77357. BABYLON.ColorGradingTexture = ColorGradingTexture;
  77358. })(BABYLON || (BABYLON = {}));
  77359. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  77360. var BABYLON;
  77361. (function (BABYLON) {
  77362. /**
  77363. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  77364. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  77365. * 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;
  77366. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  77367. */
  77368. var ColorCurves = /** @class */ (function () {
  77369. function ColorCurves() {
  77370. this._dirty = true;
  77371. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  77372. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  77373. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77374. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  77375. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77376. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  77377. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  77378. this._globalHue = 30;
  77379. this._globalDensity = 0;
  77380. this._globalSaturation = 0;
  77381. this._globalExposure = 0;
  77382. this._highlightsHue = 30;
  77383. this._highlightsDensity = 0;
  77384. this._highlightsSaturation = 0;
  77385. this._highlightsExposure = 0;
  77386. this._midtonesHue = 30;
  77387. this._midtonesDensity = 0;
  77388. this._midtonesSaturation = 0;
  77389. this._midtonesExposure = 0;
  77390. this._shadowsHue = 30;
  77391. this._shadowsDensity = 0;
  77392. this._shadowsSaturation = 0;
  77393. this._shadowsExposure = 0;
  77394. }
  77395. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  77396. /**
  77397. * Gets the global Hue value.
  77398. * 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).
  77399. */
  77400. get: function () {
  77401. return this._globalHue;
  77402. },
  77403. /**
  77404. * Sets the global Hue value.
  77405. * 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).
  77406. */
  77407. set: function (value) {
  77408. this._globalHue = value;
  77409. this._dirty = true;
  77410. },
  77411. enumerable: true,
  77412. configurable: true
  77413. });
  77414. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  77415. /**
  77416. * Gets the global Density value.
  77417. * 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.
  77418. * Values less than zero provide a filter of opposite hue.
  77419. */
  77420. get: function () {
  77421. return this._globalDensity;
  77422. },
  77423. /**
  77424. * Sets the global Density value.
  77425. * 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.
  77426. * Values less than zero provide a filter of opposite hue.
  77427. */
  77428. set: function (value) {
  77429. this._globalDensity = value;
  77430. this._dirty = true;
  77431. },
  77432. enumerable: true,
  77433. configurable: true
  77434. });
  77435. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  77436. /**
  77437. * Gets the global Saturation value.
  77438. * 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.
  77439. */
  77440. get: function () {
  77441. return this._globalSaturation;
  77442. },
  77443. /**
  77444. * Sets the global Saturation value.
  77445. * 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.
  77446. */
  77447. set: function (value) {
  77448. this._globalSaturation = value;
  77449. this._dirty = true;
  77450. },
  77451. enumerable: true,
  77452. configurable: true
  77453. });
  77454. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  77455. /**
  77456. * Gets the global Exposure value.
  77457. * 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.
  77458. */
  77459. get: function () {
  77460. return this._globalExposure;
  77461. },
  77462. /**
  77463. * Sets the global Exposure value.
  77464. * 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.
  77465. */
  77466. set: function (value) {
  77467. this._globalExposure = value;
  77468. this._dirty = true;
  77469. },
  77470. enumerable: true,
  77471. configurable: true
  77472. });
  77473. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  77474. /**
  77475. * Gets the highlights Hue value.
  77476. * 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).
  77477. */
  77478. get: function () {
  77479. return this._highlightsHue;
  77480. },
  77481. /**
  77482. * Sets the highlights Hue value.
  77483. * 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).
  77484. */
  77485. set: function (value) {
  77486. this._highlightsHue = value;
  77487. this._dirty = true;
  77488. },
  77489. enumerable: true,
  77490. configurable: true
  77491. });
  77492. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  77493. /**
  77494. * Gets the highlights Density value.
  77495. * 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.
  77496. * Values less than zero provide a filter of opposite hue.
  77497. */
  77498. get: function () {
  77499. return this._highlightsDensity;
  77500. },
  77501. /**
  77502. * Sets the highlights Density value.
  77503. * 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.
  77504. * Values less than zero provide a filter of opposite hue.
  77505. */
  77506. set: function (value) {
  77507. this._highlightsDensity = value;
  77508. this._dirty = true;
  77509. },
  77510. enumerable: true,
  77511. configurable: true
  77512. });
  77513. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  77514. /**
  77515. * Gets the highlights Saturation value.
  77516. * 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.
  77517. */
  77518. get: function () {
  77519. return this._highlightsSaturation;
  77520. },
  77521. /**
  77522. * Sets the highlights Saturation value.
  77523. * 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.
  77524. */
  77525. set: function (value) {
  77526. this._highlightsSaturation = value;
  77527. this._dirty = true;
  77528. },
  77529. enumerable: true,
  77530. configurable: true
  77531. });
  77532. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  77533. /**
  77534. * Gets the highlights Exposure value.
  77535. * 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.
  77536. */
  77537. get: function () {
  77538. return this._highlightsExposure;
  77539. },
  77540. /**
  77541. * Sets the highlights Exposure value.
  77542. * 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.
  77543. */
  77544. set: function (value) {
  77545. this._highlightsExposure = value;
  77546. this._dirty = true;
  77547. },
  77548. enumerable: true,
  77549. configurable: true
  77550. });
  77551. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  77552. /**
  77553. * Gets the midtones Hue value.
  77554. * 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).
  77555. */
  77556. get: function () {
  77557. return this._midtonesHue;
  77558. },
  77559. /**
  77560. * Sets the midtones Hue value.
  77561. * 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).
  77562. */
  77563. set: function (value) {
  77564. this._midtonesHue = value;
  77565. this._dirty = true;
  77566. },
  77567. enumerable: true,
  77568. configurable: true
  77569. });
  77570. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  77571. /**
  77572. * Gets the midtones Density value.
  77573. * 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.
  77574. * Values less than zero provide a filter of opposite hue.
  77575. */
  77576. get: function () {
  77577. return this._midtonesDensity;
  77578. },
  77579. /**
  77580. * Sets the midtones Density value.
  77581. * 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.
  77582. * Values less than zero provide a filter of opposite hue.
  77583. */
  77584. set: function (value) {
  77585. this._midtonesDensity = value;
  77586. this._dirty = true;
  77587. },
  77588. enumerable: true,
  77589. configurable: true
  77590. });
  77591. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  77592. /**
  77593. * Gets the midtones Saturation value.
  77594. * 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.
  77595. */
  77596. get: function () {
  77597. return this._midtonesSaturation;
  77598. },
  77599. /**
  77600. * Sets the midtones Saturation value.
  77601. * 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.
  77602. */
  77603. set: function (value) {
  77604. this._midtonesSaturation = value;
  77605. this._dirty = true;
  77606. },
  77607. enumerable: true,
  77608. configurable: true
  77609. });
  77610. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  77611. /**
  77612. * Gets the midtones Exposure value.
  77613. * 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.
  77614. */
  77615. get: function () {
  77616. return this._midtonesExposure;
  77617. },
  77618. /**
  77619. * Sets the midtones Exposure value.
  77620. * 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.
  77621. */
  77622. set: function (value) {
  77623. this._midtonesExposure = value;
  77624. this._dirty = true;
  77625. },
  77626. enumerable: true,
  77627. configurable: true
  77628. });
  77629. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  77630. /**
  77631. * Gets the shadows Hue value.
  77632. * 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).
  77633. */
  77634. get: function () {
  77635. return this._shadowsHue;
  77636. },
  77637. /**
  77638. * Sets the shadows Hue value.
  77639. * 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).
  77640. */
  77641. set: function (value) {
  77642. this._shadowsHue = value;
  77643. this._dirty = true;
  77644. },
  77645. enumerable: true,
  77646. configurable: true
  77647. });
  77648. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  77649. /**
  77650. * Gets the shadows Density value.
  77651. * 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.
  77652. * Values less than zero provide a filter of opposite hue.
  77653. */
  77654. get: function () {
  77655. return this._shadowsDensity;
  77656. },
  77657. /**
  77658. * Sets the shadows Density value.
  77659. * 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.
  77660. * Values less than zero provide a filter of opposite hue.
  77661. */
  77662. set: function (value) {
  77663. this._shadowsDensity = value;
  77664. this._dirty = true;
  77665. },
  77666. enumerable: true,
  77667. configurable: true
  77668. });
  77669. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  77670. /**
  77671. * Gets the shadows Saturation value.
  77672. * 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.
  77673. */
  77674. get: function () {
  77675. return this._shadowsSaturation;
  77676. },
  77677. /**
  77678. * Sets the shadows Saturation value.
  77679. * 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.
  77680. */
  77681. set: function (value) {
  77682. this._shadowsSaturation = value;
  77683. this._dirty = true;
  77684. },
  77685. enumerable: true,
  77686. configurable: true
  77687. });
  77688. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  77689. /**
  77690. * Gets the shadows Exposure value.
  77691. * 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.
  77692. */
  77693. get: function () {
  77694. return this._shadowsExposure;
  77695. },
  77696. /**
  77697. * Sets the shadows Exposure value.
  77698. * 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.
  77699. */
  77700. set: function (value) {
  77701. this._shadowsExposure = value;
  77702. this._dirty = true;
  77703. },
  77704. enumerable: true,
  77705. configurable: true
  77706. });
  77707. ColorCurves.prototype.getClassName = function () {
  77708. return "ColorCurves";
  77709. };
  77710. /**
  77711. * Binds the color curves to the shader.
  77712. * @param colorCurves The color curve to bind
  77713. * @param effect The effect to bind to
  77714. */
  77715. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  77716. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  77717. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  77718. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  77719. if (colorCurves._dirty) {
  77720. colorCurves._dirty = false;
  77721. // Fill in global info.
  77722. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  77723. // Compute highlights info.
  77724. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  77725. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  77726. // Compute midtones info.
  77727. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  77728. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  77729. // Compute shadows info.
  77730. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  77731. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  77732. // Compute deltas (neutral is midtones).
  77733. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  77734. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  77735. }
  77736. if (effect) {
  77737. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  77738. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  77739. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  77740. }
  77741. };
  77742. /**
  77743. * Prepare the list of uniforms associated with the ColorCurves effects.
  77744. * @param uniformsList The list of uniforms used in the effect
  77745. */
  77746. ColorCurves.PrepareUniforms = function (uniformsList) {
  77747. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  77748. };
  77749. /**
  77750. * Returns color grading data based on a hue, density, saturation and exposure value.
  77751. * @param filterHue The hue of the color filter.
  77752. * @param filterDensity The density of the color filter.
  77753. * @param saturation The saturation.
  77754. * @param exposure The exposure.
  77755. * @param result The result data container.
  77756. */
  77757. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  77758. if (hue == null) {
  77759. return;
  77760. }
  77761. hue = ColorCurves.clamp(hue, 0, 360);
  77762. density = ColorCurves.clamp(density, -100, 100);
  77763. saturation = ColorCurves.clamp(saturation, -100, 100);
  77764. exposure = ColorCurves.clamp(exposure, -100, 100);
  77765. // Remap the slider/config filter density with non-linear mapping and also scale by half
  77766. // so that the maximum filter density is only 50% control. This provides fine control
  77767. // for small values and reasonable range.
  77768. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  77769. density *= 0.5;
  77770. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  77771. if (density < 0) {
  77772. density *= -1;
  77773. hue = (hue + 180) % 360;
  77774. }
  77775. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  77776. result.scaleToRef(2, result);
  77777. result.a = 1 + 0.01 * saturation;
  77778. };
  77779. /**
  77780. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  77781. * @param value The input slider value in range [-100,100].
  77782. * @returns Adjusted value.
  77783. */
  77784. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  77785. value /= 100;
  77786. var x = Math.abs(value);
  77787. x = Math.pow(x, 2);
  77788. if (value < 0) {
  77789. x *= -1;
  77790. }
  77791. x *= 100;
  77792. return x;
  77793. };
  77794. /**
  77795. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  77796. * @param hue The hue (H) input.
  77797. * @param saturation The saturation (S) input.
  77798. * @param brightness The brightness (B) input.
  77799. * @result An RGBA color represented as Vector4.
  77800. */
  77801. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  77802. var h = ColorCurves.clamp(hue, 0, 360);
  77803. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  77804. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  77805. if (s === 0) {
  77806. result.r = v;
  77807. result.g = v;
  77808. result.b = v;
  77809. }
  77810. else {
  77811. // sector 0 to 5
  77812. h /= 60;
  77813. var i = Math.floor(h);
  77814. // fractional part of h
  77815. var f = h - i;
  77816. var p = v * (1 - s);
  77817. var q = v * (1 - s * f);
  77818. var t = v * (1 - s * (1 - f));
  77819. switch (i) {
  77820. case 0:
  77821. result.r = v;
  77822. result.g = t;
  77823. result.b = p;
  77824. break;
  77825. case 1:
  77826. result.r = q;
  77827. result.g = v;
  77828. result.b = p;
  77829. break;
  77830. case 2:
  77831. result.r = p;
  77832. result.g = v;
  77833. result.b = t;
  77834. break;
  77835. case 3:
  77836. result.r = p;
  77837. result.g = q;
  77838. result.b = v;
  77839. break;
  77840. case 4:
  77841. result.r = t;
  77842. result.g = p;
  77843. result.b = v;
  77844. break;
  77845. default: // case 5:
  77846. result.r = v;
  77847. result.g = p;
  77848. result.b = q;
  77849. break;
  77850. }
  77851. }
  77852. result.a = 1;
  77853. };
  77854. /**
  77855. * Returns a value clamped between min and max
  77856. * @param value The value to clamp
  77857. * @param min The minimum of value
  77858. * @param max The maximum of value
  77859. * @returns The clamped value.
  77860. */
  77861. ColorCurves.clamp = function (value, min, max) {
  77862. return Math.min(Math.max(value, min), max);
  77863. };
  77864. /**
  77865. * Clones the current color curve instance.
  77866. * @return The cloned curves
  77867. */
  77868. ColorCurves.prototype.clone = function () {
  77869. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  77870. };
  77871. /**
  77872. * Serializes the current color curve instance to a json representation.
  77873. * @return a JSON representation
  77874. */
  77875. ColorCurves.prototype.serialize = function () {
  77876. return BABYLON.SerializationHelper.Serialize(this);
  77877. };
  77878. /**
  77879. * Parses the color curve from a json representation.
  77880. * @param source the JSON source to parse
  77881. * @return The parsed curves
  77882. */
  77883. ColorCurves.Parse = function (source) {
  77884. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  77885. };
  77886. __decorate([
  77887. BABYLON.serialize()
  77888. ], ColorCurves.prototype, "_globalHue", void 0);
  77889. __decorate([
  77890. BABYLON.serialize()
  77891. ], ColorCurves.prototype, "_globalDensity", void 0);
  77892. __decorate([
  77893. BABYLON.serialize()
  77894. ], ColorCurves.prototype, "_globalSaturation", void 0);
  77895. __decorate([
  77896. BABYLON.serialize()
  77897. ], ColorCurves.prototype, "_globalExposure", void 0);
  77898. __decorate([
  77899. BABYLON.serialize()
  77900. ], ColorCurves.prototype, "_highlightsHue", void 0);
  77901. __decorate([
  77902. BABYLON.serialize()
  77903. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  77904. __decorate([
  77905. BABYLON.serialize()
  77906. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  77907. __decorate([
  77908. BABYLON.serialize()
  77909. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  77910. __decorate([
  77911. BABYLON.serialize()
  77912. ], ColorCurves.prototype, "_midtonesHue", void 0);
  77913. __decorate([
  77914. BABYLON.serialize()
  77915. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  77916. __decorate([
  77917. BABYLON.serialize()
  77918. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  77919. __decorate([
  77920. BABYLON.serialize()
  77921. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  77922. return ColorCurves;
  77923. }());
  77924. BABYLON.ColorCurves = ColorCurves;
  77925. })(BABYLON || (BABYLON = {}));
  77926. //# sourceMappingURL=babylon.colorCurves.js.map
  77927. var BABYLON;
  77928. (function (BABYLON) {
  77929. var RefractionPostProcess = /** @class */ (function (_super) {
  77930. __extends(RefractionPostProcess, _super);
  77931. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  77932. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  77933. _this.color = color;
  77934. _this.depth = depth;
  77935. _this.colorLevel = colorLevel;
  77936. _this._ownRefractionTexture = true;
  77937. _this.onActivateObservable.add(function (cam) {
  77938. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  77939. });
  77940. _this.onApplyObservable.add(function (effect) {
  77941. effect.setColor3("baseColor", _this.color);
  77942. effect.setFloat("depth", _this.depth);
  77943. effect.setFloat("colorLevel", _this.colorLevel);
  77944. effect.setTexture("refractionSampler", _this._refTexture);
  77945. });
  77946. return _this;
  77947. }
  77948. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  77949. /**
  77950. * Gets or sets the refraction texture
  77951. * Please note that you are responsible for disposing the texture if you set it manually
  77952. */
  77953. get: function () {
  77954. return this._refTexture;
  77955. },
  77956. set: function (value) {
  77957. if (this._refTexture && this._ownRefractionTexture) {
  77958. this._refTexture.dispose();
  77959. }
  77960. this._refTexture = value;
  77961. this._ownRefractionTexture = false;
  77962. },
  77963. enumerable: true,
  77964. configurable: true
  77965. });
  77966. // Methods
  77967. RefractionPostProcess.prototype.dispose = function (camera) {
  77968. if (this._refTexture && this._ownRefractionTexture) {
  77969. this._refTexture.dispose();
  77970. this._refTexture = null;
  77971. }
  77972. _super.prototype.dispose.call(this, camera);
  77973. };
  77974. return RefractionPostProcess;
  77975. }(BABYLON.PostProcess));
  77976. BABYLON.RefractionPostProcess = RefractionPostProcess;
  77977. })(BABYLON || (BABYLON = {}));
  77978. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  77979. var BABYLON;
  77980. (function (BABYLON) {
  77981. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  77982. __extends(BlackAndWhitePostProcess, _super);
  77983. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  77984. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  77985. _this.degree = 1;
  77986. _this.onApplyObservable.add(function (effect) {
  77987. effect.setFloat("degree", _this.degree);
  77988. });
  77989. return _this;
  77990. }
  77991. return BlackAndWhitePostProcess;
  77992. }(BABYLON.PostProcess));
  77993. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  77994. })(BABYLON || (BABYLON = {}));
  77995. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  77996. var BABYLON;
  77997. (function (BABYLON) {
  77998. /**
  77999. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  78000. * input texture to perform effects such as edge detection or sharpening
  78001. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78002. */
  78003. var ConvolutionPostProcess = /** @class */ (function (_super) {
  78004. __extends(ConvolutionPostProcess, _super);
  78005. /**
  78006. * Creates a new instance ConvolutionPostProcess
  78007. * @param name The name of the effect.
  78008. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  78009. * @param options The required width/height ratio to downsize to before computing the render pass.
  78010. * @param camera The camera to apply the render pass to.
  78011. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78012. * @param engine The engine which the post process will be applied. (default: current engine)
  78013. * @param reusable If the post process can be reused on the same frame. (default: false)
  78014. * @param textureType Type of textures used when performing the post process. (default: 0)
  78015. */
  78016. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  78017. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78018. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78019. _this.kernel = kernel;
  78020. _this.onApply = function (effect) {
  78021. effect.setFloat2("screenSize", _this.width, _this.height);
  78022. effect.setArray("kernel", _this.kernel);
  78023. };
  78024. return _this;
  78025. }
  78026. // Statics
  78027. /**
  78028. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78029. */
  78030. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  78031. /**
  78032. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78033. */
  78034. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  78035. /**
  78036. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78037. */
  78038. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  78039. /**
  78040. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78041. */
  78042. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  78043. /**
  78044. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78045. */
  78046. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  78047. /**
  78048. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78049. */
  78050. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  78051. return ConvolutionPostProcess;
  78052. }(BABYLON.PostProcess));
  78053. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  78054. })(BABYLON || (BABYLON = {}));
  78055. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  78056. var BABYLON;
  78057. (function (BABYLON) {
  78058. var FilterPostProcess = /** @class */ (function (_super) {
  78059. __extends(FilterPostProcess, _super);
  78060. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  78061. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  78062. _this.kernelMatrix = kernelMatrix;
  78063. _this.onApply = function (effect) {
  78064. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  78065. };
  78066. return _this;
  78067. }
  78068. return FilterPostProcess;
  78069. }(BABYLON.PostProcess));
  78070. BABYLON.FilterPostProcess = FilterPostProcess;
  78071. })(BABYLON || (BABYLON = {}));
  78072. //# sourceMappingURL=babylon.filterPostProcess.js.map
  78073. var BABYLON;
  78074. (function (BABYLON) {
  78075. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  78076. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  78077. __extends(VolumetricLightScatteringPostProcess, _super);
  78078. /**
  78079. * @constructor
  78080. * @param {string} name - The post-process name
  78081. * @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)
  78082. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  78083. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  78084. * @param {number} samples - The post-process quality, default 100
  78085. * @param {number} samplingMode - The post-process filtering mode
  78086. * @param {BABYLON.Engine} engine - The babylon engine
  78087. * @param {boolean} reusable - If the post-process is reusable
  78088. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  78089. */
  78090. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  78091. if (samples === void 0) { samples = 100; }
  78092. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78093. 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;
  78094. _this._screenCoordinates = BABYLON.Vector2.Zero();
  78095. /**
  78096. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  78097. */
  78098. _this.customMeshPosition = BABYLON.Vector3.Zero();
  78099. /**
  78100. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  78101. */
  78102. _this.useCustomMeshPosition = false;
  78103. /**
  78104. * If the post-process should inverse the light scattering direction
  78105. */
  78106. _this.invert = true;
  78107. /**
  78108. * Array containing the excluded meshes not rendered in the internal pass
  78109. */
  78110. _this.excludedMeshes = new Array();
  78111. /**
  78112. * Controls the overall intensity of the post-process
  78113. */
  78114. _this.exposure = 0.3;
  78115. /**
  78116. * Dissipates each sample's contribution in range [0, 1]
  78117. */
  78118. _this.decay = 0.96815;
  78119. /**
  78120. * Controls the overall intensity of each sample
  78121. */
  78122. _this.weight = 0.58767;
  78123. /**
  78124. * Controls the density of each sample
  78125. */
  78126. _this.density = 0.926;
  78127. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  78128. engine = scene.getEngine();
  78129. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  78130. // Configure mesh
  78131. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  78132. // Configure
  78133. _this._createPass(scene, ratio.passRatio || ratio);
  78134. _this.onActivate = function (camera) {
  78135. if (!_this.isSupported) {
  78136. _this.dispose(camera);
  78137. }
  78138. _this.onActivate = null;
  78139. };
  78140. _this.onApplyObservable.add(function (effect) {
  78141. _this._updateMeshScreenCoordinates(scene);
  78142. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  78143. effect.setFloat("exposure", _this.exposure);
  78144. effect.setFloat("decay", _this.decay);
  78145. effect.setFloat("weight", _this.weight);
  78146. effect.setFloat("density", _this.density);
  78147. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  78148. });
  78149. return _this;
  78150. }
  78151. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  78152. get: function () {
  78153. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78154. return false;
  78155. },
  78156. set: function (useDiffuseColor) {
  78157. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78158. },
  78159. enumerable: true,
  78160. configurable: true
  78161. });
  78162. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  78163. return "VolumetricLightScatteringPostProcess";
  78164. };
  78165. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  78166. var mesh = subMesh.getMesh();
  78167. // Render this.mesh as default
  78168. if (mesh === this.mesh && mesh.material) {
  78169. return mesh.material.isReady(mesh);
  78170. }
  78171. var defines = [];
  78172. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78173. var material = subMesh.getMaterial();
  78174. // Alpha test
  78175. if (material) {
  78176. if (material.needAlphaTesting()) {
  78177. defines.push("#define ALPHATEST");
  78178. }
  78179. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78180. attribs.push(BABYLON.VertexBuffer.UVKind);
  78181. defines.push("#define UV1");
  78182. }
  78183. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78184. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78185. defines.push("#define UV2");
  78186. }
  78187. }
  78188. // Bones
  78189. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78190. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78191. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78192. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78193. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  78194. }
  78195. else {
  78196. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78197. }
  78198. // Instances
  78199. if (useInstances) {
  78200. defines.push("#define INSTANCES");
  78201. attribs.push("world0");
  78202. attribs.push("world1");
  78203. attribs.push("world2");
  78204. attribs.push("world3");
  78205. }
  78206. // Get correct effect
  78207. var join = defines.join("\n");
  78208. if (this._cachedDefines !== join) {
  78209. this._cachedDefines = join;
  78210. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  78211. }
  78212. return this._volumetricLightScatteringPass.isReady();
  78213. };
  78214. /**
  78215. * Sets the new light position for light scattering effect
  78216. * @param {BABYLON.Vector3} The new custom light position
  78217. */
  78218. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  78219. this.customMeshPosition = position;
  78220. };
  78221. /**
  78222. * Returns the light position for light scattering effect
  78223. * @return {BABYLON.Vector3} The custom light position
  78224. */
  78225. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  78226. return this.customMeshPosition;
  78227. };
  78228. /**
  78229. * Disposes the internal assets and detaches the post-process from the camera
  78230. */
  78231. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  78232. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  78233. if (rttIndex !== -1) {
  78234. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  78235. }
  78236. this._volumetricLightScatteringRTT.dispose();
  78237. _super.prototype.dispose.call(this, camera);
  78238. };
  78239. /**
  78240. * Returns the render target texture used by the post-process
  78241. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  78242. */
  78243. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  78244. return this._volumetricLightScatteringRTT;
  78245. };
  78246. // Private methods
  78247. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  78248. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  78249. return true;
  78250. }
  78251. return false;
  78252. };
  78253. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  78254. var _this = this;
  78255. var engine = scene.getEngine();
  78256. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78257. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78258. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78259. this._volumetricLightScatteringRTT.renderList = null;
  78260. this._volumetricLightScatteringRTT.renderParticles = false;
  78261. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  78262. var camera = this.getCamera();
  78263. if (camera) {
  78264. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78265. }
  78266. else {
  78267. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78268. }
  78269. // Custom render function for submeshes
  78270. var renderSubMesh = function (subMesh) {
  78271. var mesh = subMesh.getRenderingMesh();
  78272. if (_this._meshExcluded(mesh)) {
  78273. return;
  78274. }
  78275. var material = subMesh.getMaterial();
  78276. if (!material) {
  78277. return;
  78278. }
  78279. var scene = mesh.getScene();
  78280. var engine = scene.getEngine();
  78281. // Culling
  78282. engine.setState(material.backFaceCulling);
  78283. // Managing instances
  78284. var batch = mesh._getInstancesRenderList(subMesh._id);
  78285. if (batch.mustReturn) {
  78286. return;
  78287. }
  78288. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78289. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  78290. var effect = _this._volumetricLightScatteringPass;
  78291. if (mesh === _this.mesh) {
  78292. if (subMesh.effect) {
  78293. effect = subMesh.effect;
  78294. }
  78295. else {
  78296. effect = material.getEffect();
  78297. }
  78298. }
  78299. engine.enableEffect(effect);
  78300. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  78301. if (mesh === _this.mesh) {
  78302. material.bind(mesh.getWorldMatrix(), mesh);
  78303. }
  78304. else {
  78305. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  78306. // Alpha test
  78307. if (material && material.needAlphaTesting()) {
  78308. var alphaTexture = material.getAlphaTestTexture();
  78309. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  78310. if (alphaTexture) {
  78311. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78312. }
  78313. }
  78314. // Bones
  78315. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78316. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78317. }
  78318. }
  78319. // Draw
  78320. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  78321. }
  78322. };
  78323. // Render target texture callbacks
  78324. var savedSceneClearColor;
  78325. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  78326. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  78327. savedSceneClearColor = scene.clearColor;
  78328. scene.clearColor = sceneClearColor;
  78329. });
  78330. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  78331. scene.clearColor = savedSceneClearColor;
  78332. });
  78333. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78334. var engine = scene.getEngine();
  78335. var index;
  78336. if (depthOnlySubMeshes.length) {
  78337. engine.setColorWrite(false);
  78338. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78339. renderSubMesh(depthOnlySubMeshes.data[index]);
  78340. }
  78341. engine.setColorWrite(true);
  78342. }
  78343. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78344. renderSubMesh(opaqueSubMeshes.data[index]);
  78345. }
  78346. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78347. renderSubMesh(alphaTestSubMeshes.data[index]);
  78348. }
  78349. if (transparentSubMeshes.length) {
  78350. // Sort sub meshes
  78351. for (index = 0; index < transparentSubMeshes.length; index++) {
  78352. var submesh = transparentSubMeshes.data[index];
  78353. var boundingInfo = submesh.getBoundingInfo();
  78354. if (boundingInfo && scene.activeCamera) {
  78355. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  78356. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  78357. }
  78358. }
  78359. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  78360. sortedArray.sort(function (a, b) {
  78361. // Alpha index first
  78362. if (a._alphaIndex > b._alphaIndex) {
  78363. return 1;
  78364. }
  78365. if (a._alphaIndex < b._alphaIndex) {
  78366. return -1;
  78367. }
  78368. // Then distance to camera
  78369. if (a._distanceToCamera < b._distanceToCamera) {
  78370. return 1;
  78371. }
  78372. if (a._distanceToCamera > b._distanceToCamera) {
  78373. return -1;
  78374. }
  78375. return 0;
  78376. });
  78377. // Render sub meshes
  78378. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  78379. for (index = 0; index < sortedArray.length; index++) {
  78380. renderSubMesh(sortedArray[index]);
  78381. }
  78382. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  78383. }
  78384. };
  78385. };
  78386. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  78387. var transform = scene.getTransformMatrix();
  78388. var meshPosition;
  78389. if (this.useCustomMeshPosition) {
  78390. meshPosition = this.customMeshPosition;
  78391. }
  78392. else if (this.attachedNode) {
  78393. meshPosition = this.attachedNode.position;
  78394. }
  78395. else {
  78396. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  78397. }
  78398. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  78399. this._screenCoordinates.x = pos.x / this._viewPort.width;
  78400. this._screenCoordinates.y = pos.y / this._viewPort.height;
  78401. if (this.invert)
  78402. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  78403. };
  78404. // Static methods
  78405. /**
  78406. * Creates a default mesh for the Volumeric Light Scattering post-process
  78407. * @param {string} The mesh name
  78408. * @param {BABYLON.Scene} The scene where to create the mesh
  78409. * @return {BABYLON.Mesh} the default mesh
  78410. */
  78411. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  78412. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  78413. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  78414. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  78415. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  78416. mesh.material = material;
  78417. return mesh;
  78418. };
  78419. __decorate([
  78420. BABYLON.serializeAsVector3()
  78421. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  78422. __decorate([
  78423. BABYLON.serialize()
  78424. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  78425. __decorate([
  78426. BABYLON.serialize()
  78427. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  78428. __decorate([
  78429. BABYLON.serializeAsMeshReference()
  78430. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  78431. __decorate([
  78432. BABYLON.serialize()
  78433. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  78434. __decorate([
  78435. BABYLON.serialize()
  78436. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  78437. __decorate([
  78438. BABYLON.serialize()
  78439. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  78440. __decorate([
  78441. BABYLON.serialize()
  78442. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  78443. __decorate([
  78444. BABYLON.serialize()
  78445. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  78446. return VolumetricLightScatteringPostProcess;
  78447. }(BABYLON.PostProcess));
  78448. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  78449. })(BABYLON || (BABYLON = {}));
  78450. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  78451. //
  78452. // This post-process allows the modification of rendered colors by using
  78453. // a 'look-up table' (LUT). This effect is also called Color Grading.
  78454. //
  78455. // The object needs to be provided an url to a texture containing the color
  78456. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  78457. // Use an image editing software to tweak the LUT to match your needs.
  78458. //
  78459. // For an example of a color LUT, see here:
  78460. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  78461. // For explanations on color grading, see here:
  78462. // http://udn.epicgames.com/Three/ColorGrading.html
  78463. //
  78464. var BABYLON;
  78465. (function (BABYLON) {
  78466. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  78467. __extends(ColorCorrectionPostProcess, _super);
  78468. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  78469. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  78470. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78471. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  78472. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78473. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78474. _this.onApply = function (effect) {
  78475. effect.setTexture("colorTable", _this._colorTableTexture);
  78476. };
  78477. return _this;
  78478. }
  78479. return ColorCorrectionPostProcess;
  78480. }(BABYLON.PostProcess));
  78481. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  78482. })(BABYLON || (BABYLON = {}));
  78483. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  78484. var BABYLON;
  78485. (function (BABYLON) {
  78486. /** Defines operator used for tonemapping */
  78487. var TonemappingOperator;
  78488. (function (TonemappingOperator) {
  78489. /** Hable */
  78490. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  78491. /** Reinhard */
  78492. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  78493. /** HejiDawson */
  78494. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  78495. /** Photographic */
  78496. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  78497. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  78498. ;
  78499. /**
  78500. * Defines a post process to apply tone mapping
  78501. */
  78502. var TonemapPostProcess = /** @class */ (function (_super) {
  78503. __extends(TonemapPostProcess, _super);
  78504. /**
  78505. * Creates a new TonemapPostProcess
  78506. * @param name defines the name of the postprocess
  78507. * @param _operator defines the operator to use
  78508. * @param exposureAdjustment defines the required exposure adjustement
  78509. * @param camera defines the camera to use (can be null)
  78510. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  78511. * @param engine defines the hosting engine (can be ignore if camera is set)
  78512. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  78513. */
  78514. function TonemapPostProcess(name, _operator,
  78515. /** Defines the required exposure adjustement */
  78516. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  78517. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78518. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78519. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  78520. _this._operator = _operator;
  78521. _this.exposureAdjustment = exposureAdjustment;
  78522. var defines = "#define ";
  78523. if (_this._operator === TonemappingOperator.Hable)
  78524. defines += "HABLE_TONEMAPPING";
  78525. else if (_this._operator === TonemappingOperator.Reinhard)
  78526. defines += "REINHARD_TONEMAPPING";
  78527. else if (_this._operator === TonemappingOperator.HejiDawson)
  78528. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  78529. else if (_this._operator === TonemappingOperator.Photographic)
  78530. defines += "PHOTOGRAPHIC_TONEMAPPING";
  78531. //sadly a second call to create the effect.
  78532. _this.updateEffect(defines);
  78533. _this.onApply = function (effect) {
  78534. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  78535. };
  78536. return _this;
  78537. }
  78538. return TonemapPostProcess;
  78539. }(BABYLON.PostProcess));
  78540. BABYLON.TonemapPostProcess = TonemapPostProcess;
  78541. })(BABYLON || (BABYLON = {}));
  78542. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  78543. var BABYLON;
  78544. (function (BABYLON) {
  78545. var DisplayPassPostProcess = /** @class */ (function (_super) {
  78546. __extends(DisplayPassPostProcess, _super);
  78547. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  78548. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  78549. }
  78550. return DisplayPassPostProcess;
  78551. }(BABYLON.PostProcess));
  78552. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  78553. })(BABYLON || (BABYLON = {}));
  78554. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  78555. var BABYLON;
  78556. (function (BABYLON) {
  78557. var HighlightsPostProcess = /** @class */ (function (_super) {
  78558. __extends(HighlightsPostProcess, _super);
  78559. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  78560. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78561. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78562. }
  78563. return HighlightsPostProcess;
  78564. }(BABYLON.PostProcess));
  78565. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  78566. })(BABYLON || (BABYLON = {}));
  78567. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  78568. var BABYLON;
  78569. (function (BABYLON) {
  78570. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  78571. __extends(ImageProcessingPostProcess, _super);
  78572. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  78573. if (camera === void 0) { camera = null; }
  78574. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78575. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  78576. _this._fromLinearSpace = true;
  78577. /**
  78578. * Defines cache preventing GC.
  78579. */
  78580. _this._defines = {
  78581. IMAGEPROCESSING: false,
  78582. VIGNETTE: false,
  78583. VIGNETTEBLENDMODEMULTIPLY: false,
  78584. VIGNETTEBLENDMODEOPAQUE: false,
  78585. TONEMAPPING: false,
  78586. CONTRAST: false,
  78587. COLORCURVES: false,
  78588. COLORGRADING: false,
  78589. COLORGRADING3D: false,
  78590. FROMLINEARSPACE: false,
  78591. SAMPLER3DGREENDEPTH: false,
  78592. SAMPLER3DBGRMAP: false,
  78593. IMAGEPROCESSINGPOSTPROCESS: false,
  78594. EXPOSURE: false,
  78595. };
  78596. // Setup the configuration as forced by the constructor. This would then not force the
  78597. // scene materials output in linear space and let untouched the default forward pass.
  78598. if (imageProcessingConfiguration) {
  78599. imageProcessingConfiguration.applyByPostProcess = true;
  78600. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  78601. // This will cause the shader to be compiled
  78602. _this.fromLinearSpace = false;
  78603. }
  78604. // Setup the default processing configuration to the scene.
  78605. else {
  78606. _this._attachImageProcessingConfiguration(null, true);
  78607. _this.imageProcessingConfiguration.applyByPostProcess = true;
  78608. }
  78609. _this.onApply = function (effect) {
  78610. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  78611. };
  78612. return _this;
  78613. }
  78614. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  78615. /**
  78616. * Gets the image processing configuration used either in this material.
  78617. */
  78618. get: function () {
  78619. return this._imageProcessingConfiguration;
  78620. },
  78621. /**
  78622. * Sets the Default image processing configuration used either in the this material.
  78623. *
  78624. * If sets to null, the scene one is in use.
  78625. */
  78626. set: function (value) {
  78627. this._attachImageProcessingConfiguration(value);
  78628. },
  78629. enumerable: true,
  78630. configurable: true
  78631. });
  78632. /**
  78633. * Attaches a new image processing configuration to the PBR Material.
  78634. * @param configuration
  78635. */
  78636. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  78637. var _this = this;
  78638. if (doNotBuild === void 0) { doNotBuild = false; }
  78639. if (configuration === this._imageProcessingConfiguration) {
  78640. return;
  78641. }
  78642. // Detaches observer.
  78643. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78644. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78645. }
  78646. // Pick the scene configuration if needed.
  78647. if (!configuration) {
  78648. var scene = null;
  78649. var engine = this.getEngine();
  78650. var camera = this.getCamera();
  78651. if (camera) {
  78652. scene = camera.getScene();
  78653. }
  78654. else if (engine && engine.scenes) {
  78655. var scenes = engine.scenes;
  78656. scene = scenes[scenes.length - 1];
  78657. }
  78658. else {
  78659. scene = BABYLON.Engine.LastCreatedScene;
  78660. }
  78661. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  78662. }
  78663. else {
  78664. this._imageProcessingConfiguration = configuration;
  78665. }
  78666. // Attaches observer.
  78667. if (this._imageProcessingConfiguration) {
  78668. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  78669. _this._updateParameters();
  78670. });
  78671. }
  78672. // Ensure the effect will be rebuilt.
  78673. if (!doNotBuild) {
  78674. this._updateParameters();
  78675. }
  78676. };
  78677. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  78678. /**
  78679. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78680. */
  78681. get: function () {
  78682. return this.imageProcessingConfiguration.colorCurves;
  78683. },
  78684. /**
  78685. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78686. */
  78687. set: function (value) {
  78688. this.imageProcessingConfiguration.colorCurves = value;
  78689. },
  78690. enumerable: true,
  78691. configurable: true
  78692. });
  78693. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  78694. /**
  78695. * Gets wether the color curves effect is enabled.
  78696. */
  78697. get: function () {
  78698. return this.imageProcessingConfiguration.colorCurvesEnabled;
  78699. },
  78700. /**
  78701. * Sets wether the color curves effect is enabled.
  78702. */
  78703. set: function (value) {
  78704. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  78705. },
  78706. enumerable: true,
  78707. configurable: true
  78708. });
  78709. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  78710. /**
  78711. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  78712. */
  78713. get: function () {
  78714. return this.imageProcessingConfiguration.colorGradingTexture;
  78715. },
  78716. /**
  78717. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  78718. */
  78719. set: function (value) {
  78720. this.imageProcessingConfiguration.colorGradingTexture = value;
  78721. },
  78722. enumerable: true,
  78723. configurable: true
  78724. });
  78725. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  78726. /**
  78727. * Gets wether the color grading effect is enabled.
  78728. */
  78729. get: function () {
  78730. return this.imageProcessingConfiguration.colorGradingEnabled;
  78731. },
  78732. /**
  78733. * Gets wether the color grading effect is enabled.
  78734. */
  78735. set: function (value) {
  78736. this.imageProcessingConfiguration.colorGradingEnabled = value;
  78737. },
  78738. enumerable: true,
  78739. configurable: true
  78740. });
  78741. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  78742. /**
  78743. * Gets exposure used in the effect.
  78744. */
  78745. get: function () {
  78746. return this.imageProcessingConfiguration.exposure;
  78747. },
  78748. /**
  78749. * Sets exposure used in the effect.
  78750. */
  78751. set: function (value) {
  78752. this.imageProcessingConfiguration.exposure = value;
  78753. },
  78754. enumerable: true,
  78755. configurable: true
  78756. });
  78757. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  78758. /**
  78759. * Gets wether tonemapping is enabled or not.
  78760. */
  78761. get: function () {
  78762. return this._imageProcessingConfiguration.toneMappingEnabled;
  78763. },
  78764. /**
  78765. * Sets wether tonemapping is enabled or not
  78766. */
  78767. set: function (value) {
  78768. this._imageProcessingConfiguration.toneMappingEnabled = value;
  78769. },
  78770. enumerable: true,
  78771. configurable: true
  78772. });
  78773. ;
  78774. ;
  78775. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  78776. /**
  78777. * Gets contrast used in the effect.
  78778. */
  78779. get: function () {
  78780. return this.imageProcessingConfiguration.contrast;
  78781. },
  78782. /**
  78783. * Sets contrast used in the effect.
  78784. */
  78785. set: function (value) {
  78786. this.imageProcessingConfiguration.contrast = value;
  78787. },
  78788. enumerable: true,
  78789. configurable: true
  78790. });
  78791. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  78792. /**
  78793. * Gets Vignette stretch size.
  78794. */
  78795. get: function () {
  78796. return this.imageProcessingConfiguration.vignetteStretch;
  78797. },
  78798. /**
  78799. * Sets Vignette stretch size.
  78800. */
  78801. set: function (value) {
  78802. this.imageProcessingConfiguration.vignetteStretch = value;
  78803. },
  78804. enumerable: true,
  78805. configurable: true
  78806. });
  78807. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  78808. /**
  78809. * Gets Vignette centre X Offset.
  78810. */
  78811. get: function () {
  78812. return this.imageProcessingConfiguration.vignetteCentreX;
  78813. },
  78814. /**
  78815. * Sets Vignette centre X Offset.
  78816. */
  78817. set: function (value) {
  78818. this.imageProcessingConfiguration.vignetteCentreX = value;
  78819. },
  78820. enumerable: true,
  78821. configurable: true
  78822. });
  78823. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  78824. /**
  78825. * Gets Vignette centre Y Offset.
  78826. */
  78827. get: function () {
  78828. return this.imageProcessingConfiguration.vignetteCentreY;
  78829. },
  78830. /**
  78831. * Sets Vignette centre Y Offset.
  78832. */
  78833. set: function (value) {
  78834. this.imageProcessingConfiguration.vignetteCentreY = value;
  78835. },
  78836. enumerable: true,
  78837. configurable: true
  78838. });
  78839. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  78840. /**
  78841. * Gets Vignette weight or intensity of the vignette effect.
  78842. */
  78843. get: function () {
  78844. return this.imageProcessingConfiguration.vignetteWeight;
  78845. },
  78846. /**
  78847. * Sets Vignette weight or intensity of the vignette effect.
  78848. */
  78849. set: function (value) {
  78850. this.imageProcessingConfiguration.vignetteWeight = value;
  78851. },
  78852. enumerable: true,
  78853. configurable: true
  78854. });
  78855. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  78856. /**
  78857. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78858. * if vignetteEnabled is set to true.
  78859. */
  78860. get: function () {
  78861. return this.imageProcessingConfiguration.vignetteColor;
  78862. },
  78863. /**
  78864. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78865. * if vignetteEnabled is set to true.
  78866. */
  78867. set: function (value) {
  78868. this.imageProcessingConfiguration.vignetteColor = value;
  78869. },
  78870. enumerable: true,
  78871. configurable: true
  78872. });
  78873. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  78874. /**
  78875. * Gets Camera field of view used by the Vignette effect.
  78876. */
  78877. get: function () {
  78878. return this.imageProcessingConfiguration.vignetteCameraFov;
  78879. },
  78880. /**
  78881. * Sets Camera field of view used by the Vignette effect.
  78882. */
  78883. set: function (value) {
  78884. this.imageProcessingConfiguration.vignetteCameraFov = value;
  78885. },
  78886. enumerable: true,
  78887. configurable: true
  78888. });
  78889. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  78890. /**
  78891. * Gets the vignette blend mode allowing different kind of effect.
  78892. */
  78893. get: function () {
  78894. return this.imageProcessingConfiguration.vignetteBlendMode;
  78895. },
  78896. /**
  78897. * Sets the vignette blend mode allowing different kind of effect.
  78898. */
  78899. set: function (value) {
  78900. this.imageProcessingConfiguration.vignetteBlendMode = value;
  78901. },
  78902. enumerable: true,
  78903. configurable: true
  78904. });
  78905. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  78906. /**
  78907. * Gets wether the vignette effect is enabled.
  78908. */
  78909. get: function () {
  78910. return this.imageProcessingConfiguration.vignetteEnabled;
  78911. },
  78912. /**
  78913. * Sets wether the vignette effect is enabled.
  78914. */
  78915. set: function (value) {
  78916. this.imageProcessingConfiguration.vignetteEnabled = value;
  78917. },
  78918. enumerable: true,
  78919. configurable: true
  78920. });
  78921. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  78922. /**
  78923. * Gets wether the input of the processing is in Gamma or Linear Space.
  78924. */
  78925. get: function () {
  78926. return this._fromLinearSpace;
  78927. },
  78928. /**
  78929. * Sets wether the input of the processing is in Gamma or Linear Space.
  78930. */
  78931. set: function (value) {
  78932. if (this._fromLinearSpace === value) {
  78933. return;
  78934. }
  78935. this._fromLinearSpace = value;
  78936. this._updateParameters();
  78937. },
  78938. enumerable: true,
  78939. configurable: true
  78940. });
  78941. ImageProcessingPostProcess.prototype.getClassName = function () {
  78942. return "ImageProcessingPostProcess";
  78943. };
  78944. ImageProcessingPostProcess.prototype._updateParameters = function () {
  78945. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  78946. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  78947. var defines = "";
  78948. for (var define in this._defines) {
  78949. if (this._defines[define]) {
  78950. defines += "#define " + define + ";\r\n";
  78951. }
  78952. }
  78953. var samplers = ["textureSampler"];
  78954. var uniforms = ["scale"];
  78955. if (BABYLON.ImageProcessingConfiguration) {
  78956. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  78957. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  78958. }
  78959. this.updateEffect(defines, uniforms, samplers);
  78960. };
  78961. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  78962. _super.prototype.dispose.call(this, camera);
  78963. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78964. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78965. }
  78966. if (this._imageProcessingConfiguration) {
  78967. this.imageProcessingConfiguration.applyByPostProcess = false;
  78968. }
  78969. };
  78970. __decorate([
  78971. BABYLON.serialize()
  78972. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  78973. return ImageProcessingPostProcess;
  78974. }(BABYLON.PostProcess));
  78975. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  78976. })(BABYLON || (BABYLON = {}));
  78977. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  78978. var BABYLON;
  78979. (function (BABYLON) {
  78980. /**
  78981. * Class used to store bone information
  78982. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78983. */
  78984. var Bone = /** @class */ (function (_super) {
  78985. __extends(Bone, _super);
  78986. /**
  78987. * Create a new bone
  78988. * @param name defines the bone name
  78989. * @param skeleton defines the parent skeleton
  78990. * @param parentBone defines the parent (can be null if the bone is the root)
  78991. * @param localMatrix defines the local matrix
  78992. * @param restPose defines the rest pose matrix
  78993. * @param baseMatrix defines the base matrix
  78994. * @param index defines index of the bone in the hiearchy
  78995. */
  78996. function Bone(
  78997. /**
  78998. * defines the bone name
  78999. */
  79000. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  79001. if (parentBone === void 0) { parentBone = null; }
  79002. if (localMatrix === void 0) { localMatrix = null; }
  79003. if (restPose === void 0) { restPose = null; }
  79004. if (baseMatrix === void 0) { baseMatrix = null; }
  79005. if (index === void 0) { index = null; }
  79006. var _this = _super.call(this, name, skeleton.getScene()) || this;
  79007. _this.name = name;
  79008. /**
  79009. * Gets the list of child bones
  79010. */
  79011. _this.children = new Array();
  79012. /** Gets the animations associated with this bone */
  79013. _this.animations = new Array();
  79014. /**
  79015. * @hidden Internal only
  79016. * Set this value to map this bone to a different index in the transform matrices
  79017. * Set this value to -1 to exclude the bone from the transform matrices
  79018. */
  79019. _this._index = null;
  79020. _this._absoluteTransform = new BABYLON.Matrix();
  79021. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  79022. _this._scalingDeterminant = 1;
  79023. _this._worldTransform = new BABYLON.Matrix();
  79024. _this._needToDecompose = true;
  79025. _this._needToCompose = false;
  79026. _this._skeleton = skeleton;
  79027. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  79028. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  79029. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  79030. _this._index = index;
  79031. skeleton.bones.push(_this);
  79032. _this.setParent(parentBone, false);
  79033. if (baseMatrix || localMatrix) {
  79034. _this._updateDifferenceMatrix();
  79035. }
  79036. return _this;
  79037. }
  79038. Object.defineProperty(Bone.prototype, "_matrix", {
  79039. /** @hidden */
  79040. get: function () {
  79041. this._compose();
  79042. return this._localMatrix;
  79043. },
  79044. /** @hidden */
  79045. set: function (value) {
  79046. this._localMatrix.copyFrom(value);
  79047. this._needToDecompose = true;
  79048. },
  79049. enumerable: true,
  79050. configurable: true
  79051. });
  79052. // Members
  79053. /**
  79054. * Gets the parent skeleton
  79055. * @returns a skeleton
  79056. */
  79057. Bone.prototype.getSkeleton = function () {
  79058. return this._skeleton;
  79059. };
  79060. /**
  79061. * Gets parent bone
  79062. * @returns a bone or null if the bone is the root of the bone hierarchy
  79063. */
  79064. Bone.prototype.getParent = function () {
  79065. return this._parent;
  79066. };
  79067. /**
  79068. * Sets the parent bone
  79069. * @param parent defines the parent (can be null if the bone is the root)
  79070. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79071. */
  79072. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  79073. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79074. if (this._parent === parent) {
  79075. return;
  79076. }
  79077. if (this._parent) {
  79078. var index = this._parent.children.indexOf(this);
  79079. if (index !== -1) {
  79080. this._parent.children.splice(index, 1);
  79081. }
  79082. }
  79083. this._parent = parent;
  79084. if (this._parent) {
  79085. this._parent.children.push(this);
  79086. }
  79087. if (updateDifferenceMatrix) {
  79088. this._updateDifferenceMatrix();
  79089. }
  79090. this.markAsDirty();
  79091. };
  79092. /**
  79093. * Gets the local matrix
  79094. * @returns a matrix
  79095. */
  79096. Bone.prototype.getLocalMatrix = function () {
  79097. this._compose();
  79098. return this._localMatrix;
  79099. };
  79100. /**
  79101. * Gets the base matrix (initial matrix which remains unchanged)
  79102. * @returns a matrix
  79103. */
  79104. Bone.prototype.getBaseMatrix = function () {
  79105. return this._baseMatrix;
  79106. };
  79107. /**
  79108. * Gets the rest pose matrix
  79109. * @returns a matrix
  79110. */
  79111. Bone.prototype.getRestPose = function () {
  79112. return this._restPose;
  79113. };
  79114. /**
  79115. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  79116. */
  79117. Bone.prototype.getWorldMatrix = function () {
  79118. return this._worldTransform;
  79119. };
  79120. /**
  79121. * Sets the local matrix to rest pose matrix
  79122. */
  79123. Bone.prototype.returnToRest = function () {
  79124. this.updateMatrix(this._restPose.clone());
  79125. };
  79126. /**
  79127. * Gets the inverse of the absolute transform matrix.
  79128. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  79129. * @returns a matrix
  79130. */
  79131. Bone.prototype.getInvertedAbsoluteTransform = function () {
  79132. return this._invertedAbsoluteTransform;
  79133. };
  79134. /**
  79135. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  79136. * @returns a matrix
  79137. */
  79138. Bone.prototype.getAbsoluteTransform = function () {
  79139. return this._absoluteTransform;
  79140. };
  79141. Object.defineProperty(Bone.prototype, "position", {
  79142. // Properties (matches AbstractMesh properties)
  79143. /** Gets or sets current position (in local space) */
  79144. get: function () {
  79145. this._decompose();
  79146. return this._localPosition;
  79147. },
  79148. set: function (newPosition) {
  79149. this._decompose();
  79150. this._localPosition.copyFrom(newPosition);
  79151. this._markAsDirtyAndCompose();
  79152. },
  79153. enumerable: true,
  79154. configurable: true
  79155. });
  79156. Object.defineProperty(Bone.prototype, "rotation", {
  79157. /** Gets or sets current rotation (in local space) */
  79158. get: function () {
  79159. return this.getRotation();
  79160. },
  79161. set: function (newRotation) {
  79162. this.setRotation(newRotation);
  79163. },
  79164. enumerable: true,
  79165. configurable: true
  79166. });
  79167. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  79168. /** Gets or sets current rotation quaternion (in local space) */
  79169. get: function () {
  79170. this._decompose();
  79171. return this._localRotation;
  79172. },
  79173. set: function (newRotation) {
  79174. this.setRotationQuaternion(newRotation);
  79175. },
  79176. enumerable: true,
  79177. configurable: true
  79178. });
  79179. Object.defineProperty(Bone.prototype, "scaling", {
  79180. /** Gets or sets current scaling (in local space) */
  79181. get: function () {
  79182. return this.getScale();
  79183. },
  79184. set: function (newScaling) {
  79185. this.setScale(newScaling);
  79186. },
  79187. enumerable: true,
  79188. configurable: true
  79189. });
  79190. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  79191. /**
  79192. * Gets the animation properties override
  79193. */
  79194. get: function () {
  79195. return this._skeleton.animationPropertiesOverride;
  79196. },
  79197. enumerable: true,
  79198. configurable: true
  79199. });
  79200. // Methods
  79201. Bone.prototype._decompose = function () {
  79202. if (!this._needToDecompose) {
  79203. return;
  79204. }
  79205. this._needToDecompose = false;
  79206. if (!this._localScaling) {
  79207. this._localScaling = BABYLON.Vector3.Zero();
  79208. this._localRotation = BABYLON.Quaternion.Zero();
  79209. this._localPosition = BABYLON.Vector3.Zero();
  79210. }
  79211. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  79212. };
  79213. Bone.prototype._compose = function () {
  79214. if (!this._needToCompose) {
  79215. return;
  79216. }
  79217. this._needToCompose = false;
  79218. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  79219. };
  79220. /**
  79221. * Update the base and local matrices
  79222. * @param matrix defines the new base or local matrix
  79223. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79224. * @param updateLocalMatrix defines if the local matrix should be updated
  79225. */
  79226. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  79227. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79228. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  79229. this._baseMatrix.copyFrom(matrix);
  79230. if (updateDifferenceMatrix) {
  79231. this._updateDifferenceMatrix();
  79232. }
  79233. if (updateLocalMatrix) {
  79234. this._localMatrix.copyFrom(matrix);
  79235. this._markAsDirtyAndDecompose();
  79236. }
  79237. else {
  79238. this.markAsDirty();
  79239. }
  79240. };
  79241. /** @hidden */
  79242. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  79243. if (updateChildren === void 0) { updateChildren = true; }
  79244. if (!rootMatrix) {
  79245. rootMatrix = this._baseMatrix;
  79246. }
  79247. if (this._parent) {
  79248. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79249. }
  79250. else {
  79251. this._absoluteTransform.copyFrom(rootMatrix);
  79252. }
  79253. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  79254. if (updateChildren) {
  79255. for (var index = 0; index < this.children.length; index++) {
  79256. this.children[index]._updateDifferenceMatrix();
  79257. }
  79258. }
  79259. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  79260. };
  79261. /**
  79262. * Flag the bone as dirty (Forcing it to update everything)
  79263. */
  79264. Bone.prototype.markAsDirty = function () {
  79265. this._currentRenderId++;
  79266. this._childRenderId++;
  79267. this._skeleton._markAsDirty();
  79268. };
  79269. Bone.prototype._markAsDirtyAndCompose = function () {
  79270. this.markAsDirty();
  79271. this._needToCompose = true;
  79272. };
  79273. Bone.prototype._markAsDirtyAndDecompose = function () {
  79274. this.markAsDirty();
  79275. this._needToDecompose = true;
  79276. };
  79277. /**
  79278. * Copy an animation range from another bone
  79279. * @param source defines the source bone
  79280. * @param rangeName defines the range name to copy
  79281. * @param frameOffset defines the frame offset
  79282. * @param rescaleAsRequired defines if rescaling must be applied if required
  79283. * @param skelDimensionsRatio defines the scaling ratio
  79284. * @returns true if operation was successful
  79285. */
  79286. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  79287. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79288. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  79289. // all animation may be coming from a library skeleton, so may need to create animation
  79290. if (this.animations.length === 0) {
  79291. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  79292. this.animations[0].setKeys([]);
  79293. }
  79294. // get animation info / verify there is such a range from the source bone
  79295. var sourceRange = source.animations[0].getRange(rangeName);
  79296. if (!sourceRange) {
  79297. return false;
  79298. }
  79299. var from = sourceRange.from;
  79300. var to = sourceRange.to;
  79301. var sourceKeys = source.animations[0].getKeys();
  79302. // rescaling prep
  79303. var sourceBoneLength = source.length;
  79304. var sourceParent = source.getParent();
  79305. var parent = this.getParent();
  79306. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  79307. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  79308. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  79309. var destKeys = this.animations[0].getKeys();
  79310. // loop vars declaration
  79311. var orig;
  79312. var origTranslation;
  79313. var mat;
  79314. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  79315. orig = sourceKeys[key];
  79316. if (orig.frame >= from && orig.frame <= to) {
  79317. if (rescaleAsRequired) {
  79318. mat = orig.value.clone();
  79319. // scale based on parent ratio, when bone has parent
  79320. if (parentScalingReqd) {
  79321. origTranslation = mat.getTranslation();
  79322. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  79323. // scale based on skeleton dimension ratio when root bone, and value is passed
  79324. }
  79325. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  79326. origTranslation = mat.getTranslation();
  79327. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  79328. // use original when root bone, and no data for skelDimensionsRatio
  79329. }
  79330. else {
  79331. mat = orig.value;
  79332. }
  79333. }
  79334. else {
  79335. mat = orig.value;
  79336. }
  79337. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  79338. }
  79339. }
  79340. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  79341. return true;
  79342. };
  79343. /**
  79344. * Translate the bone in local or world space
  79345. * @param vec The amount to translate the bone
  79346. * @param space The space that the translation is in
  79347. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79348. */
  79349. Bone.prototype.translate = function (vec, space, mesh) {
  79350. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79351. var lm = this.getLocalMatrix();
  79352. if (space == BABYLON.Space.LOCAL) {
  79353. lm.m[12] += vec.x;
  79354. lm.m[13] += vec.y;
  79355. lm.m[14] += vec.z;
  79356. }
  79357. else {
  79358. var wm = null;
  79359. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79360. if (mesh) {
  79361. wm = mesh.getWorldMatrix();
  79362. }
  79363. this._skeleton.computeAbsoluteTransforms();
  79364. var tmat = Bone._tmpMats[0];
  79365. var tvec = Bone._tmpVecs[0];
  79366. if (this._parent) {
  79367. if (mesh && wm) {
  79368. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79369. tmat.multiplyToRef(wm, tmat);
  79370. }
  79371. else {
  79372. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79373. }
  79374. }
  79375. tmat.m[12] = 0;
  79376. tmat.m[13] = 0;
  79377. tmat.m[14] = 0;
  79378. tmat.invert();
  79379. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  79380. lm.m[12] += tvec.x;
  79381. lm.m[13] += tvec.y;
  79382. lm.m[14] += tvec.z;
  79383. }
  79384. this._markAsDirtyAndDecompose();
  79385. };
  79386. /**
  79387. * Set the postion of the bone in local or world space
  79388. * @param position The position to set the bone
  79389. * @param space The space that the position is in
  79390. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79391. */
  79392. Bone.prototype.setPosition = function (position, space, mesh) {
  79393. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79394. var lm = this.getLocalMatrix();
  79395. if (space == BABYLON.Space.LOCAL) {
  79396. lm.m[12] = position.x;
  79397. lm.m[13] = position.y;
  79398. lm.m[14] = position.z;
  79399. }
  79400. else {
  79401. var wm = null;
  79402. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79403. if (mesh) {
  79404. wm = mesh.getWorldMatrix();
  79405. }
  79406. this._skeleton.computeAbsoluteTransforms();
  79407. var tmat = Bone._tmpMats[0];
  79408. var vec = Bone._tmpVecs[0];
  79409. if (this._parent) {
  79410. if (mesh && wm) {
  79411. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79412. tmat.multiplyToRef(wm, tmat);
  79413. }
  79414. else {
  79415. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79416. }
  79417. }
  79418. tmat.invert();
  79419. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  79420. lm.m[12] = vec.x;
  79421. lm.m[13] = vec.y;
  79422. lm.m[14] = vec.z;
  79423. }
  79424. this._markAsDirtyAndDecompose();
  79425. };
  79426. /**
  79427. * Set the absolute position of the bone (world space)
  79428. * @param position The position to set the bone
  79429. * @param mesh The mesh that this bone is attached to
  79430. */
  79431. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  79432. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  79433. };
  79434. /**
  79435. * Scale the bone on the x, y and z axes (in local space)
  79436. * @param x The amount to scale the bone on the x axis
  79437. * @param y The amount to scale the bone on the y axis
  79438. * @param z The amount to scale the bone on the z axis
  79439. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  79440. */
  79441. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  79442. if (scaleChildren === void 0) { scaleChildren = false; }
  79443. var locMat = this.getLocalMatrix();
  79444. // Apply new scaling on top of current local matrix
  79445. var scaleMat = Bone._tmpMats[0];
  79446. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  79447. scaleMat.multiplyToRef(locMat, locMat);
  79448. // Invert scaling matrix and apply the inverse to all children
  79449. scaleMat.invert();
  79450. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  79451. var child = _a[_i];
  79452. var cm = child.getLocalMatrix();
  79453. cm.multiplyToRef(scaleMat, cm);
  79454. cm.m[12] *= x;
  79455. cm.m[13] *= y;
  79456. cm.m[14] *= z;
  79457. child._markAsDirtyAndDecompose();
  79458. }
  79459. this._markAsDirtyAndDecompose();
  79460. if (scaleChildren) {
  79461. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  79462. var child = _c[_b];
  79463. child.scale(x, y, z, scaleChildren);
  79464. }
  79465. }
  79466. };
  79467. /**
  79468. * Set the bone scaling in local space
  79469. * @param scale defines the scaling vector
  79470. */
  79471. Bone.prototype.setScale = function (scale) {
  79472. this._decompose();
  79473. this._localScaling.copyFrom(scale);
  79474. this._markAsDirtyAndCompose();
  79475. };
  79476. /**
  79477. * Gets the current scaling in local space
  79478. * @returns the current scaling vector
  79479. */
  79480. Bone.prototype.getScale = function () {
  79481. this._decompose();
  79482. return this._localScaling;
  79483. };
  79484. /**
  79485. * Gets the current scaling in local space and stores it in a target vector
  79486. * @param result defines the target vector
  79487. */
  79488. Bone.prototype.getScaleToRef = function (result) {
  79489. this._decompose();
  79490. result.copyFrom(this._localScaling);
  79491. };
  79492. /**
  79493. * Set the yaw, pitch, and roll of the bone in local or world space
  79494. * @param yaw The rotation of the bone on the y axis
  79495. * @param pitch The rotation of the bone on the x axis
  79496. * @param roll The rotation of the bone on the z axis
  79497. * @param space The space that the axes of rotation are in
  79498. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79499. */
  79500. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  79501. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79502. if (space === BABYLON.Space.LOCAL) {
  79503. var quat = Bone._tmpQuat;
  79504. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  79505. this.setRotationQuaternion(quat, space, mesh);
  79506. return;
  79507. }
  79508. var rotMatInv = Bone._tmpMats[0];
  79509. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79510. return;
  79511. }
  79512. var rotMat = Bone._tmpMats[1];
  79513. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  79514. rotMatInv.multiplyToRef(rotMat, rotMat);
  79515. this._rotateWithMatrix(rotMat, space, mesh);
  79516. };
  79517. /**
  79518. * Add a rotation to the bone on an axis in local or world space
  79519. * @param axis The axis to rotate the bone on
  79520. * @param amount The amount to rotate the bone
  79521. * @param space The space that the axis is in
  79522. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79523. */
  79524. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  79525. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79526. var rmat = Bone._tmpMats[0];
  79527. rmat.m[12] = 0;
  79528. rmat.m[13] = 0;
  79529. rmat.m[14] = 0;
  79530. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  79531. this._rotateWithMatrix(rmat, space, mesh);
  79532. };
  79533. /**
  79534. * Set the rotation of the bone to a particular axis angle in local or world space
  79535. * @param axis The axis to rotate the bone on
  79536. * @param angle The angle that the bone should be rotated to
  79537. * @param space The space that the axis is in
  79538. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79539. */
  79540. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  79541. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79542. if (space === BABYLON.Space.LOCAL) {
  79543. var quat = Bone._tmpQuat;
  79544. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  79545. this.setRotationQuaternion(quat, space, mesh);
  79546. return;
  79547. }
  79548. var rotMatInv = Bone._tmpMats[0];
  79549. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79550. return;
  79551. }
  79552. var rotMat = Bone._tmpMats[1];
  79553. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  79554. rotMatInv.multiplyToRef(rotMat, rotMat);
  79555. this._rotateWithMatrix(rotMat, space, mesh);
  79556. };
  79557. /**
  79558. * Set the euler rotation of the bone in local of world space
  79559. * @param rotation The euler rotation that the bone should be set to
  79560. * @param space The space that the rotation is in
  79561. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79562. */
  79563. Bone.prototype.setRotation = function (rotation, space, mesh) {
  79564. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79565. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  79566. };
  79567. /**
  79568. * Set the quaternion rotation of the bone in local of world space
  79569. * @param quat The quaternion rotation that the bone should be set to
  79570. * @param space The space that the rotation is in
  79571. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79572. */
  79573. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  79574. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79575. if (space === BABYLON.Space.LOCAL) {
  79576. this._decompose();
  79577. this._localRotation.copyFrom(quat);
  79578. this._markAsDirtyAndCompose();
  79579. return;
  79580. }
  79581. var rotMatInv = Bone._tmpMats[0];
  79582. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79583. return;
  79584. }
  79585. var rotMat = Bone._tmpMats[1];
  79586. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  79587. rotMatInv.multiplyToRef(rotMat, rotMat);
  79588. this._rotateWithMatrix(rotMat, space, mesh);
  79589. };
  79590. /**
  79591. * Set the rotation matrix of the bone in local of world space
  79592. * @param rotMat The rotation matrix that the bone should be set to
  79593. * @param space The space that the rotation is in
  79594. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79595. */
  79596. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  79597. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79598. if (space === BABYLON.Space.LOCAL) {
  79599. var quat = Bone._tmpQuat;
  79600. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  79601. this.setRotationQuaternion(quat, space, mesh);
  79602. return;
  79603. }
  79604. var rotMatInv = Bone._tmpMats[0];
  79605. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79606. return;
  79607. }
  79608. var rotMat2 = Bone._tmpMats[1];
  79609. rotMat2.copyFrom(rotMat);
  79610. rotMatInv.multiplyToRef(rotMat, rotMat2);
  79611. this._rotateWithMatrix(rotMat2, space, mesh);
  79612. };
  79613. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  79614. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79615. var lmat = this.getLocalMatrix();
  79616. var lx = lmat.m[12];
  79617. var ly = lmat.m[13];
  79618. var lz = lmat.m[14];
  79619. var parent = this.getParent();
  79620. var parentScale = Bone._tmpMats[3];
  79621. var parentScaleInv = Bone._tmpMats[4];
  79622. if (parent && space == BABYLON.Space.WORLD) {
  79623. if (mesh) {
  79624. parentScale.copyFrom(mesh.getWorldMatrix());
  79625. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  79626. }
  79627. else {
  79628. parentScale.copyFrom(parent.getAbsoluteTransform());
  79629. }
  79630. parentScaleInv.copyFrom(parentScale);
  79631. parentScaleInv.invert();
  79632. lmat.multiplyToRef(parentScale, lmat);
  79633. lmat.multiplyToRef(rmat, lmat);
  79634. lmat.multiplyToRef(parentScaleInv, lmat);
  79635. }
  79636. else {
  79637. if (space == BABYLON.Space.WORLD && mesh) {
  79638. parentScale.copyFrom(mesh.getWorldMatrix());
  79639. parentScaleInv.copyFrom(parentScale);
  79640. parentScaleInv.invert();
  79641. lmat.multiplyToRef(parentScale, lmat);
  79642. lmat.multiplyToRef(rmat, lmat);
  79643. lmat.multiplyToRef(parentScaleInv, lmat);
  79644. }
  79645. else {
  79646. lmat.multiplyToRef(rmat, lmat);
  79647. }
  79648. }
  79649. lmat.m[12] = lx;
  79650. lmat.m[13] = ly;
  79651. lmat.m[14] = lz;
  79652. this.computeAbsoluteTransforms();
  79653. this._markAsDirtyAndDecompose();
  79654. };
  79655. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  79656. var scaleMatrix = Bone._tmpMats[2];
  79657. rotMatInv.copyFrom(this.getAbsoluteTransform());
  79658. if (mesh) {
  79659. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  79660. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  79661. }
  79662. rotMatInv.invert();
  79663. if (isNaN(rotMatInv.m[0])) {
  79664. // Matrix failed to invert.
  79665. // This can happen if scale is zero for example.
  79666. return false;
  79667. }
  79668. scaleMatrix.m[0] *= this._scalingDeterminant;
  79669. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  79670. return true;
  79671. };
  79672. /**
  79673. * Get the position of the bone in local or world space
  79674. * @param space The space that the returned position is in
  79675. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79676. * @returns The position of the bone
  79677. */
  79678. Bone.prototype.getPosition = function (space, mesh) {
  79679. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79680. if (mesh === void 0) { mesh = null; }
  79681. var pos = BABYLON.Vector3.Zero();
  79682. this.getPositionToRef(space, mesh, pos);
  79683. return pos;
  79684. };
  79685. /**
  79686. * Copy the position of the bone to a vector3 in local or world space
  79687. * @param space The space that the returned position is in
  79688. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79689. * @param result The vector3 to copy the position to
  79690. */
  79691. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  79692. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79693. if (space == BABYLON.Space.LOCAL) {
  79694. var lm = this.getLocalMatrix();
  79695. result.x = lm.m[12];
  79696. result.y = lm.m[13];
  79697. result.z = lm.m[14];
  79698. }
  79699. else {
  79700. var wm = null;
  79701. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79702. if (mesh) {
  79703. wm = mesh.getWorldMatrix();
  79704. }
  79705. this._skeleton.computeAbsoluteTransforms();
  79706. var tmat = Bone._tmpMats[0];
  79707. if (mesh && wm) {
  79708. tmat.copyFrom(this.getAbsoluteTransform());
  79709. tmat.multiplyToRef(wm, tmat);
  79710. }
  79711. else {
  79712. tmat = this.getAbsoluteTransform();
  79713. }
  79714. result.x = tmat.m[12];
  79715. result.y = tmat.m[13];
  79716. result.z = tmat.m[14];
  79717. }
  79718. };
  79719. /**
  79720. * Get the absolute position of the bone (world space)
  79721. * @param mesh The mesh that this bone is attached to
  79722. * @returns The absolute position of the bone
  79723. */
  79724. Bone.prototype.getAbsolutePosition = function (mesh) {
  79725. if (mesh === void 0) { mesh = null; }
  79726. var pos = BABYLON.Vector3.Zero();
  79727. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  79728. return pos;
  79729. };
  79730. /**
  79731. * Copy the absolute position of the bone (world space) to the result param
  79732. * @param mesh The mesh that this bone is attached to
  79733. * @param result The vector3 to copy the absolute position to
  79734. */
  79735. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  79736. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  79737. };
  79738. /**
  79739. * Compute the absolute transforms of this bone and its children
  79740. */
  79741. Bone.prototype.computeAbsoluteTransforms = function () {
  79742. this._compose();
  79743. if (this._parent) {
  79744. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79745. }
  79746. else {
  79747. this._absoluteTransform.copyFrom(this._localMatrix);
  79748. var poseMatrix = this._skeleton.getPoseMatrix();
  79749. if (poseMatrix) {
  79750. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  79751. }
  79752. }
  79753. var children = this.children;
  79754. var len = children.length;
  79755. for (var i = 0; i < len; i++) {
  79756. children[i].computeAbsoluteTransforms();
  79757. }
  79758. };
  79759. /**
  79760. * Get the world direction from an axis that is in the local space of the bone
  79761. * @param localAxis The local direction that is used to compute the world direction
  79762. * @param mesh The mesh that this bone is attached to
  79763. * @returns The world direction
  79764. */
  79765. Bone.prototype.getDirection = function (localAxis, mesh) {
  79766. if (mesh === void 0) { mesh = null; }
  79767. var result = BABYLON.Vector3.Zero();
  79768. this.getDirectionToRef(localAxis, mesh, result);
  79769. return result;
  79770. };
  79771. /**
  79772. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  79773. * @param localAxis The local direction that is used to compute the world direction
  79774. * @param mesh The mesh that this bone is attached to
  79775. * @param result The vector3 that the world direction will be copied to
  79776. */
  79777. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  79778. if (mesh === void 0) { mesh = null; }
  79779. var wm = null;
  79780. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79781. if (mesh) {
  79782. wm = mesh.getWorldMatrix();
  79783. }
  79784. this._skeleton.computeAbsoluteTransforms();
  79785. var mat = Bone._tmpMats[0];
  79786. mat.copyFrom(this.getAbsoluteTransform());
  79787. if (mesh && wm) {
  79788. mat.multiplyToRef(wm, mat);
  79789. }
  79790. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  79791. result.normalize();
  79792. };
  79793. /**
  79794. * Get the euler rotation of the bone in local or world space
  79795. * @param space The space that the rotation should be in
  79796. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79797. * @returns The euler rotation
  79798. */
  79799. Bone.prototype.getRotation = function (space, mesh) {
  79800. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79801. if (mesh === void 0) { mesh = null; }
  79802. var result = BABYLON.Vector3.Zero();
  79803. this.getRotationToRef(space, mesh, result);
  79804. return result;
  79805. };
  79806. /**
  79807. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  79808. * @param space The space that the rotation should be in
  79809. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79810. * @param result The vector3 that the rotation should be copied to
  79811. */
  79812. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  79813. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79814. if (mesh === void 0) { mesh = null; }
  79815. var quat = Bone._tmpQuat;
  79816. this.getRotationQuaternionToRef(space, mesh, quat);
  79817. quat.toEulerAnglesToRef(result);
  79818. };
  79819. /**
  79820. * Get the quaternion rotation of the bone in either local or world space
  79821. * @param space The space that the rotation should be in
  79822. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79823. * @returns The quaternion rotation
  79824. */
  79825. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  79826. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79827. if (mesh === void 0) { mesh = null; }
  79828. var result = BABYLON.Quaternion.Identity();
  79829. this.getRotationQuaternionToRef(space, mesh, result);
  79830. return result;
  79831. };
  79832. /**
  79833. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  79834. * @param space The space that the rotation should be in
  79835. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79836. * @param result The quaternion that the rotation should be copied to
  79837. */
  79838. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  79839. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79840. if (mesh === void 0) { mesh = null; }
  79841. if (space == BABYLON.Space.LOCAL) {
  79842. this._decompose();
  79843. result.copyFrom(this._localRotation);
  79844. }
  79845. else {
  79846. var mat = Bone._tmpMats[0];
  79847. var amat = this.getAbsoluteTransform();
  79848. if (mesh) {
  79849. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79850. }
  79851. else {
  79852. mat.copyFrom(amat);
  79853. }
  79854. mat.m[0] *= this._scalingDeterminant;
  79855. mat.m[1] *= this._scalingDeterminant;
  79856. mat.m[2] *= this._scalingDeterminant;
  79857. mat.decompose(undefined, result, undefined);
  79858. }
  79859. };
  79860. /**
  79861. * Get the rotation matrix of the bone in local or world space
  79862. * @param space The space that the rotation should be in
  79863. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79864. * @returns The rotation matrix
  79865. */
  79866. Bone.prototype.getRotationMatrix = function (space, mesh) {
  79867. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79868. var result = BABYLON.Matrix.Identity();
  79869. this.getRotationMatrixToRef(space, mesh, result);
  79870. return result;
  79871. };
  79872. /**
  79873. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  79874. * @param space The space that the rotation should be in
  79875. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79876. * @param result The quaternion that the rotation should be copied to
  79877. */
  79878. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  79879. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79880. if (space == BABYLON.Space.LOCAL) {
  79881. this.getLocalMatrix().getRotationMatrixToRef(result);
  79882. }
  79883. else {
  79884. var mat = Bone._tmpMats[0];
  79885. var amat = this.getAbsoluteTransform();
  79886. if (mesh) {
  79887. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79888. }
  79889. else {
  79890. mat.copyFrom(amat);
  79891. }
  79892. mat.m[0] *= this._scalingDeterminant;
  79893. mat.m[1] *= this._scalingDeterminant;
  79894. mat.m[2] *= this._scalingDeterminant;
  79895. mat.getRotationMatrixToRef(result);
  79896. }
  79897. };
  79898. /**
  79899. * Get the world position of a point that is in the local space of the bone
  79900. * @param position The local position
  79901. * @param mesh The mesh that this bone is attached to
  79902. * @returns The world position
  79903. */
  79904. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  79905. if (mesh === void 0) { mesh = null; }
  79906. var result = BABYLON.Vector3.Zero();
  79907. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  79908. return result;
  79909. };
  79910. /**
  79911. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  79912. * @param position The local position
  79913. * @param mesh The mesh that this bone is attached to
  79914. * @param result The vector3 that the world position should be copied to
  79915. */
  79916. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  79917. if (mesh === void 0) { mesh = null; }
  79918. var wm = null;
  79919. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79920. if (mesh) {
  79921. wm = mesh.getWorldMatrix();
  79922. }
  79923. this._skeleton.computeAbsoluteTransforms();
  79924. var tmat = Bone._tmpMats[0];
  79925. if (mesh && wm) {
  79926. tmat.copyFrom(this.getAbsoluteTransform());
  79927. tmat.multiplyToRef(wm, tmat);
  79928. }
  79929. else {
  79930. tmat = this.getAbsoluteTransform();
  79931. }
  79932. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79933. };
  79934. /**
  79935. * Get the local position of a point that is in world space
  79936. * @param position The world position
  79937. * @param mesh The mesh that this bone is attached to
  79938. * @returns The local position
  79939. */
  79940. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  79941. if (mesh === void 0) { mesh = null; }
  79942. var result = BABYLON.Vector3.Zero();
  79943. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  79944. return result;
  79945. };
  79946. /**
  79947. * Get the local position of a point that is in world space and copy it to the result param
  79948. * @param position The world position
  79949. * @param mesh The mesh that this bone is attached to
  79950. * @param result The vector3 that the local position should be copied to
  79951. */
  79952. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  79953. if (mesh === void 0) { mesh = null; }
  79954. var wm = null;
  79955. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79956. if (mesh) {
  79957. wm = mesh.getWorldMatrix();
  79958. }
  79959. this._skeleton.computeAbsoluteTransforms();
  79960. var tmat = Bone._tmpMats[0];
  79961. tmat.copyFrom(this.getAbsoluteTransform());
  79962. if (mesh && wm) {
  79963. tmat.multiplyToRef(wm, tmat);
  79964. }
  79965. tmat.invert();
  79966. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79967. };
  79968. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79969. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  79970. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79971. return Bone;
  79972. }(BABYLON.Node));
  79973. BABYLON.Bone = Bone;
  79974. })(BABYLON || (BABYLON = {}));
  79975. //# sourceMappingURL=babylon.bone.js.map
  79976. var BABYLON;
  79977. (function (BABYLON) {
  79978. /**
  79979. * Class used to apply inverse kinematics to bones
  79980. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  79981. */
  79982. var BoneIKController = /** @class */ (function () {
  79983. /**
  79984. * Creates a new BoneIKController
  79985. * @param mesh defines the mesh to control
  79986. * @param bone defines the bone to control
  79987. * @param options defines options to set up the controller
  79988. */
  79989. function BoneIKController(mesh, bone, options) {
  79990. /**
  79991. * Gets or sets the target position
  79992. */
  79993. this.targetPosition = BABYLON.Vector3.Zero();
  79994. /**
  79995. * Gets or sets the pole target position
  79996. */
  79997. this.poleTargetPosition = BABYLON.Vector3.Zero();
  79998. /**
  79999. * Gets or sets the pole target local offset
  80000. */
  80001. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  80002. /**
  80003. * Gets or sets the pole angle
  80004. */
  80005. this.poleAngle = 0;
  80006. /**
  80007. * 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)
  80008. */
  80009. this.slerpAmount = 1;
  80010. this._bone1Quat = BABYLON.Quaternion.Identity();
  80011. this._bone1Mat = BABYLON.Matrix.Identity();
  80012. this._bone2Ang = Math.PI;
  80013. this._maxAngle = Math.PI;
  80014. this._rightHandedSystem = false;
  80015. this._bendAxis = BABYLON.Vector3.Right();
  80016. this._slerping = false;
  80017. this._adjustRoll = 0;
  80018. this._bone2 = bone;
  80019. this._bone1 = bone.getParent();
  80020. if (!this._bone1) {
  80021. return;
  80022. }
  80023. this.mesh = mesh;
  80024. var bonePos = bone.getPosition();
  80025. if (bone.getAbsoluteTransform().determinant() > 0) {
  80026. this._rightHandedSystem = true;
  80027. this._bendAxis.x = 0;
  80028. this._bendAxis.y = 0;
  80029. this._bendAxis.z = -1;
  80030. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  80031. this._adjustRoll = Math.PI * .5;
  80032. this._bendAxis.z = 1;
  80033. }
  80034. }
  80035. if (this._bone1.length) {
  80036. var boneScale1 = this._bone1.getScale();
  80037. var boneScale2 = this._bone2.getScale();
  80038. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  80039. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  80040. }
  80041. else if (this._bone1.children[0]) {
  80042. mesh.computeWorldMatrix(true);
  80043. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  80044. var pos2 = this._bone2.getAbsolutePosition(mesh);
  80045. var pos3 = this._bone1.getAbsolutePosition(mesh);
  80046. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  80047. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  80048. }
  80049. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  80050. this.maxAngle = Math.PI;
  80051. if (options) {
  80052. if (options.targetMesh) {
  80053. this.targetMesh = options.targetMesh;
  80054. this.targetMesh.computeWorldMatrix(true);
  80055. }
  80056. if (options.poleTargetMesh) {
  80057. this.poleTargetMesh = options.poleTargetMesh;
  80058. this.poleTargetMesh.computeWorldMatrix(true);
  80059. }
  80060. else if (options.poleTargetBone) {
  80061. this.poleTargetBone = options.poleTargetBone;
  80062. }
  80063. else if (this._bone1.getParent()) {
  80064. this.poleTargetBone = this._bone1.getParent();
  80065. }
  80066. if (options.poleTargetLocalOffset) {
  80067. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  80068. }
  80069. if (options.poleAngle) {
  80070. this.poleAngle = options.poleAngle;
  80071. }
  80072. if (options.bendAxis) {
  80073. this._bendAxis.copyFrom(options.bendAxis);
  80074. }
  80075. if (options.maxAngle) {
  80076. this.maxAngle = options.maxAngle;
  80077. }
  80078. if (options.slerpAmount) {
  80079. this.slerpAmount = options.slerpAmount;
  80080. }
  80081. }
  80082. }
  80083. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  80084. /**
  80085. * Gets or sets maximum allowed angle
  80086. */
  80087. get: function () {
  80088. return this._maxAngle;
  80089. },
  80090. set: function (value) {
  80091. this._setMaxAngle(value);
  80092. },
  80093. enumerable: true,
  80094. configurable: true
  80095. });
  80096. BoneIKController.prototype._setMaxAngle = function (ang) {
  80097. if (ang < 0) {
  80098. ang = 0;
  80099. }
  80100. if (ang > Math.PI || ang == undefined) {
  80101. ang = Math.PI;
  80102. }
  80103. this._maxAngle = ang;
  80104. var a = this._bone1Length;
  80105. var b = this._bone2Length;
  80106. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  80107. };
  80108. /**
  80109. * Force the controller to update the bones
  80110. */
  80111. BoneIKController.prototype.update = function () {
  80112. var bone1 = this._bone1;
  80113. if (!bone1) {
  80114. return;
  80115. }
  80116. var target = this.targetPosition;
  80117. var poleTarget = this.poleTargetPosition;
  80118. var mat1 = BoneIKController._tmpMats[0];
  80119. var mat2 = BoneIKController._tmpMats[1];
  80120. if (this.targetMesh) {
  80121. target.copyFrom(this.targetMesh.getAbsolutePosition());
  80122. }
  80123. if (this.poleTargetBone) {
  80124. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  80125. }
  80126. else if (this.poleTargetMesh) {
  80127. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  80128. }
  80129. var bonePos = BoneIKController._tmpVecs[0];
  80130. var zaxis = BoneIKController._tmpVecs[1];
  80131. var xaxis = BoneIKController._tmpVecs[2];
  80132. var yaxis = BoneIKController._tmpVecs[3];
  80133. var upAxis = BoneIKController._tmpVecs[4];
  80134. var _tmpQuat = BoneIKController._tmpQuat;
  80135. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  80136. poleTarget.subtractToRef(bonePos, upAxis);
  80137. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  80138. upAxis.y = 1;
  80139. }
  80140. else {
  80141. upAxis.normalize();
  80142. }
  80143. target.subtractToRef(bonePos, yaxis);
  80144. yaxis.normalize();
  80145. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  80146. zaxis.normalize();
  80147. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  80148. xaxis.normalize();
  80149. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  80150. var a = this._bone1Length;
  80151. var b = this._bone2Length;
  80152. var c = BABYLON.Vector3.Distance(bonePos, target);
  80153. if (this._maxReach > 0) {
  80154. c = Math.min(this._maxReach, c);
  80155. }
  80156. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  80157. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  80158. if (acosa > 1) {
  80159. acosa = 1;
  80160. }
  80161. if (acosb > 1) {
  80162. acosb = 1;
  80163. }
  80164. if (acosa < -1) {
  80165. acosa = -1;
  80166. }
  80167. if (acosb < -1) {
  80168. acosb = -1;
  80169. }
  80170. var angA = Math.acos(acosa);
  80171. var angB = Math.acos(acosb);
  80172. var angC = -angA - angB;
  80173. if (this._rightHandedSystem) {
  80174. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  80175. mat2.multiplyToRef(mat1, mat1);
  80176. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  80177. mat2.multiplyToRef(mat1, mat1);
  80178. }
  80179. else {
  80180. var _tmpVec = BoneIKController._tmpVecs[5];
  80181. _tmpVec.copyFrom(this._bendAxis);
  80182. _tmpVec.x *= -1;
  80183. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  80184. mat2.multiplyToRef(mat1, mat1);
  80185. }
  80186. if (this.poleAngle) {
  80187. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  80188. mat1.multiplyToRef(mat2, mat1);
  80189. }
  80190. if (this._bone1) {
  80191. if (this.slerpAmount < 1) {
  80192. if (!this._slerping) {
  80193. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  80194. }
  80195. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  80196. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  80197. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  80198. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  80199. this._slerping = true;
  80200. }
  80201. else {
  80202. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  80203. this._bone1Mat.copyFrom(mat1);
  80204. this._slerping = false;
  80205. }
  80206. }
  80207. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  80208. this._bone2Ang = angC;
  80209. };
  80210. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80211. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  80212. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80213. return BoneIKController;
  80214. }());
  80215. BABYLON.BoneIKController = BoneIKController;
  80216. })(BABYLON || (BABYLON = {}));
  80217. //# sourceMappingURL=babylon.boneIKController.js.map
  80218. var BABYLON;
  80219. (function (BABYLON) {
  80220. /**
  80221. * Class used to make a bone look toward a point in space
  80222. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  80223. */
  80224. var BoneLookController = /** @class */ (function () {
  80225. /**
  80226. * Create a BoneLookController
  80227. * @param mesh the mesh that the bone belongs to
  80228. * @param bone the bone that will be looking to the target
  80229. * @param target the target Vector3 to look at
  80230. * @param settings optional settings:
  80231. * * maxYaw: the maximum angle the bone will yaw to
  80232. * * minYaw: the minimum angle the bone will yaw to
  80233. * * maxPitch: the maximum angle the bone will pitch to
  80234. * * minPitch: the minimum angle the bone will yaw to
  80235. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  80236. * * upAxis: the up axis of the coordinate system
  80237. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  80238. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  80239. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  80240. * * adjustYaw: used to make an adjustment to the yaw of the bone
  80241. * * adjustPitch: used to make an adjustment to the pitch of the bone
  80242. * * adjustRoll: used to make an adjustment to the roll of the bone
  80243. **/
  80244. function BoneLookController(mesh, bone, target, options) {
  80245. /**
  80246. * The up axis of the coordinate system that is used when the bone is rotated
  80247. */
  80248. this.upAxis = BABYLON.Vector3.Up();
  80249. /**
  80250. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  80251. */
  80252. this.upAxisSpace = BABYLON.Space.LOCAL;
  80253. /**
  80254. * Used to make an adjustment to the yaw of the bone
  80255. */
  80256. this.adjustYaw = 0;
  80257. /**
  80258. * Used to make an adjustment to the pitch of the bone
  80259. */
  80260. this.adjustPitch = 0;
  80261. /**
  80262. * Used to make an adjustment to the roll of the bone
  80263. */
  80264. this.adjustRoll = 0;
  80265. /**
  80266. * 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)
  80267. */
  80268. this.slerpAmount = 1;
  80269. this._boneQuat = BABYLON.Quaternion.Identity();
  80270. this._slerping = false;
  80271. this._firstFrameSkipped = false;
  80272. this._fowardAxis = BABYLON.Vector3.Forward();
  80273. this.mesh = mesh;
  80274. this.bone = bone;
  80275. this.target = target;
  80276. if (options) {
  80277. if (options.adjustYaw) {
  80278. this.adjustYaw = options.adjustYaw;
  80279. }
  80280. if (options.adjustPitch) {
  80281. this.adjustPitch = options.adjustPitch;
  80282. }
  80283. if (options.adjustRoll) {
  80284. this.adjustRoll = options.adjustRoll;
  80285. }
  80286. if (options.maxYaw != null) {
  80287. this.maxYaw = options.maxYaw;
  80288. }
  80289. else {
  80290. this.maxYaw = Math.PI;
  80291. }
  80292. if (options.minYaw != null) {
  80293. this.minYaw = options.minYaw;
  80294. }
  80295. else {
  80296. this.minYaw = -Math.PI;
  80297. }
  80298. if (options.maxPitch != null) {
  80299. this.maxPitch = options.maxPitch;
  80300. }
  80301. else {
  80302. this.maxPitch = Math.PI;
  80303. }
  80304. if (options.minPitch != null) {
  80305. this.minPitch = options.minPitch;
  80306. }
  80307. else {
  80308. this.minPitch = -Math.PI;
  80309. }
  80310. if (options.slerpAmount != null) {
  80311. this.slerpAmount = options.slerpAmount;
  80312. }
  80313. if (options.upAxis != null) {
  80314. this.upAxis = options.upAxis;
  80315. }
  80316. if (options.upAxisSpace != null) {
  80317. this.upAxisSpace = options.upAxisSpace;
  80318. }
  80319. if (options.yawAxis != null || options.pitchAxis != null) {
  80320. var newYawAxis = BABYLON.Axis.Y;
  80321. var newPitchAxis = BABYLON.Axis.X;
  80322. if (options.yawAxis != null) {
  80323. newYawAxis = options.yawAxis.clone();
  80324. newYawAxis.normalize();
  80325. }
  80326. if (options.pitchAxis != null) {
  80327. newPitchAxis = options.pitchAxis.clone();
  80328. newPitchAxis.normalize();
  80329. }
  80330. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  80331. this._transformYawPitch = BABYLON.Matrix.Identity();
  80332. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  80333. this._transformYawPitchInv = this._transformYawPitch.clone();
  80334. this._transformYawPitch.invert();
  80335. }
  80336. }
  80337. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  80338. this.upAxisSpace = BABYLON.Space.LOCAL;
  80339. }
  80340. }
  80341. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  80342. /**
  80343. * Gets or sets the minimum yaw angle that the bone can look to
  80344. */
  80345. get: function () {
  80346. return this._minYaw;
  80347. },
  80348. set: function (value) {
  80349. this._minYaw = value;
  80350. this._minYawSin = Math.sin(value);
  80351. this._minYawCos = Math.cos(value);
  80352. if (this._maxYaw != null) {
  80353. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80354. this._yawRange = this._maxYaw - this._minYaw;
  80355. }
  80356. },
  80357. enumerable: true,
  80358. configurable: true
  80359. });
  80360. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  80361. /**
  80362. * Gets or sets the maximum yaw angle that the bone can look to
  80363. */
  80364. get: function () {
  80365. return this._maxYaw;
  80366. },
  80367. set: function (value) {
  80368. this._maxYaw = value;
  80369. this._maxYawSin = Math.sin(value);
  80370. this._maxYawCos = Math.cos(value);
  80371. if (this._minYaw != null) {
  80372. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80373. this._yawRange = this._maxYaw - this._minYaw;
  80374. }
  80375. },
  80376. enumerable: true,
  80377. configurable: true
  80378. });
  80379. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  80380. /**
  80381. * Gets or sets the minimum pitch angle that the bone can look to
  80382. */
  80383. get: function () {
  80384. return this._minPitch;
  80385. },
  80386. set: function (value) {
  80387. this._minPitch = value;
  80388. this._minPitchTan = Math.tan(value);
  80389. },
  80390. enumerable: true,
  80391. configurable: true
  80392. });
  80393. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  80394. /**
  80395. * Gets or sets the maximum pitch angle that the bone can look to
  80396. */
  80397. get: function () {
  80398. return this._maxPitch;
  80399. },
  80400. set: function (value) {
  80401. this._maxPitch = value;
  80402. this._maxPitchTan = Math.tan(value);
  80403. },
  80404. enumerable: true,
  80405. configurable: true
  80406. });
  80407. /**
  80408. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  80409. */
  80410. BoneLookController.prototype.update = function () {
  80411. //skip the first frame when slerping so that the mesh rotation is correct
  80412. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  80413. this._firstFrameSkipped = true;
  80414. return;
  80415. }
  80416. var bone = this.bone;
  80417. var bonePos = BoneLookController._tmpVecs[0];
  80418. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  80419. var target = this.target;
  80420. var _tmpMat1 = BoneLookController._tmpMats[0];
  80421. var _tmpMat2 = BoneLookController._tmpMats[1];
  80422. var mesh = this.mesh;
  80423. var parentBone = bone.getParent();
  80424. var upAxis = BoneLookController._tmpVecs[1];
  80425. upAxis.copyFrom(this.upAxis);
  80426. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  80427. if (this._transformYawPitch) {
  80428. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  80429. }
  80430. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  80431. }
  80432. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  80433. mesh.getDirectionToRef(upAxis, upAxis);
  80434. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  80435. upAxis.normalize();
  80436. }
  80437. }
  80438. var checkYaw = false;
  80439. var checkPitch = false;
  80440. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  80441. checkYaw = true;
  80442. }
  80443. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  80444. checkPitch = true;
  80445. }
  80446. if (checkYaw || checkPitch) {
  80447. var spaceMat = BoneLookController._tmpMats[2];
  80448. var spaceMatInv = BoneLookController._tmpMats[3];
  80449. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  80450. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  80451. }
  80452. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  80453. spaceMat.copyFrom(mesh.getWorldMatrix());
  80454. }
  80455. else {
  80456. var forwardAxis = BoneLookController._tmpVecs[2];
  80457. forwardAxis.copyFrom(this._fowardAxis);
  80458. if (this._transformYawPitch) {
  80459. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  80460. }
  80461. if (parentBone) {
  80462. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  80463. }
  80464. else {
  80465. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  80466. }
  80467. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  80468. rightAxis.normalize();
  80469. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  80470. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  80471. }
  80472. spaceMat.invertToRef(spaceMatInv);
  80473. var xzlen = null;
  80474. if (checkPitch) {
  80475. var localTarget = BoneLookController._tmpVecs[3];
  80476. target.subtractToRef(bonePos, localTarget);
  80477. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80478. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80479. var pitch = Math.atan2(localTarget.y, xzlen);
  80480. var newPitch = pitch;
  80481. if (pitch > this._maxPitch) {
  80482. localTarget.y = this._maxPitchTan * xzlen;
  80483. newPitch = this._maxPitch;
  80484. }
  80485. else if (pitch < this._minPitch) {
  80486. localTarget.y = this._minPitchTan * xzlen;
  80487. newPitch = this._minPitch;
  80488. }
  80489. if (pitch != newPitch) {
  80490. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  80491. localTarget.addInPlace(bonePos);
  80492. target = localTarget;
  80493. }
  80494. }
  80495. if (checkYaw) {
  80496. var localTarget = BoneLookController._tmpVecs[4];
  80497. target.subtractToRef(bonePos, localTarget);
  80498. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80499. var yaw = Math.atan2(localTarget.x, localTarget.z);
  80500. var newYaw = yaw;
  80501. if (yaw > this._maxYaw || yaw < this._minYaw) {
  80502. if (xzlen == null) {
  80503. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80504. }
  80505. if (this._yawRange > Math.PI) {
  80506. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  80507. localTarget.z = this._maxYawCos * xzlen;
  80508. localTarget.x = this._maxYawSin * xzlen;
  80509. newYaw = this._maxYaw;
  80510. }
  80511. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  80512. localTarget.z = this._minYawCos * xzlen;
  80513. localTarget.x = this._minYawSin * xzlen;
  80514. newYaw = this._minYaw;
  80515. }
  80516. }
  80517. else {
  80518. if (yaw > this._maxYaw) {
  80519. localTarget.z = this._maxYawCos * xzlen;
  80520. localTarget.x = this._maxYawSin * xzlen;
  80521. newYaw = this._maxYaw;
  80522. }
  80523. else if (yaw < this._minYaw) {
  80524. localTarget.z = this._minYawCos * xzlen;
  80525. localTarget.x = this._minYawSin * xzlen;
  80526. newYaw = this._minYaw;
  80527. }
  80528. }
  80529. }
  80530. if (this._slerping && this._yawRange > Math.PI) {
  80531. //are we going to be crossing into the min/max region?
  80532. var boneFwd = BoneLookController._tmpVecs[8];
  80533. boneFwd.copyFrom(BABYLON.Axis.Z);
  80534. if (this._transformYawPitch) {
  80535. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  80536. }
  80537. var boneRotMat = BoneLookController._tmpMats[4];
  80538. this._boneQuat.toRotationMatrix(boneRotMat);
  80539. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  80540. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  80541. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  80542. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  80543. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  80544. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  80545. if (angBtwTar > angBtwMidYaw) {
  80546. if (xzlen == null) {
  80547. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80548. }
  80549. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  80550. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  80551. if (angBtwMin < angBtwMax) {
  80552. newYaw = boneYaw + Math.PI * .75;
  80553. localTarget.z = Math.cos(newYaw) * xzlen;
  80554. localTarget.x = Math.sin(newYaw) * xzlen;
  80555. }
  80556. else {
  80557. newYaw = boneYaw - Math.PI * .75;
  80558. localTarget.z = Math.cos(newYaw) * xzlen;
  80559. localTarget.x = Math.sin(newYaw) * xzlen;
  80560. }
  80561. }
  80562. }
  80563. if (yaw != newYaw) {
  80564. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  80565. localTarget.addInPlace(bonePos);
  80566. target = localTarget;
  80567. }
  80568. }
  80569. }
  80570. var zaxis = BoneLookController._tmpVecs[5];
  80571. var xaxis = BoneLookController._tmpVecs[6];
  80572. var yaxis = BoneLookController._tmpVecs[7];
  80573. var _tmpQuat = BoneLookController._tmpQuat;
  80574. target.subtractToRef(bonePos, zaxis);
  80575. zaxis.normalize();
  80576. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  80577. xaxis.normalize();
  80578. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  80579. yaxis.normalize();
  80580. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  80581. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  80582. return;
  80583. }
  80584. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  80585. return;
  80586. }
  80587. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  80588. return;
  80589. }
  80590. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  80591. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  80592. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  80593. }
  80594. if (this.slerpAmount < 1) {
  80595. if (!this._slerping) {
  80596. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  80597. }
  80598. if (this._transformYawPitch) {
  80599. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  80600. }
  80601. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  80602. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  80603. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  80604. this._slerping = true;
  80605. }
  80606. else {
  80607. if (this._transformYawPitch) {
  80608. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  80609. }
  80610. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  80611. this._slerping = false;
  80612. }
  80613. };
  80614. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  80615. var angDiff = ang2 - ang1;
  80616. angDiff %= Math.PI * 2;
  80617. if (angDiff > Math.PI) {
  80618. angDiff -= Math.PI * 2;
  80619. }
  80620. else if (angDiff < -Math.PI) {
  80621. angDiff += Math.PI * 2;
  80622. }
  80623. return angDiff;
  80624. };
  80625. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  80626. ang1 %= (2 * Math.PI);
  80627. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  80628. ang2 %= (2 * Math.PI);
  80629. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  80630. var ab = 0;
  80631. if (ang1 < ang2) {
  80632. ab = ang2 - ang1;
  80633. }
  80634. else {
  80635. ab = ang1 - ang2;
  80636. }
  80637. if (ab > Math.PI) {
  80638. ab = Math.PI * 2 - ab;
  80639. }
  80640. return ab;
  80641. };
  80642. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  80643. ang %= (2 * Math.PI);
  80644. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  80645. ang1 %= (2 * Math.PI);
  80646. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  80647. ang2 %= (2 * Math.PI);
  80648. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  80649. if (ang1 < ang2) {
  80650. if (ang > ang1 && ang < ang2) {
  80651. return true;
  80652. }
  80653. }
  80654. else {
  80655. if (ang > ang2 && ang < ang1) {
  80656. return true;
  80657. }
  80658. }
  80659. return false;
  80660. };
  80661. 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()];
  80662. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  80663. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80664. return BoneLookController;
  80665. }());
  80666. BABYLON.BoneLookController = BoneLookController;
  80667. })(BABYLON || (BABYLON = {}));
  80668. //# sourceMappingURL=babylon.boneLookController.js.map
  80669. var BABYLON;
  80670. (function (BABYLON) {
  80671. /**
  80672. * Class used to handle skinning animations
  80673. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  80674. */
  80675. var Skeleton = /** @class */ (function () {
  80676. /**
  80677. * Creates a new skeleton
  80678. * @param name defines the skeleton name
  80679. * @param id defines the skeleton Id
  80680. * @param scene defines the hosting scene
  80681. */
  80682. function Skeleton(
  80683. /** defines the skeleton name */
  80684. name,
  80685. /** defines the skeleton Id */
  80686. id, scene) {
  80687. this.name = name;
  80688. this.id = id;
  80689. /**
  80690. * Gets the list of child bones
  80691. */
  80692. this.bones = new Array();
  80693. /**
  80694. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  80695. */
  80696. this.needInitialSkinMatrix = false;
  80697. this._isDirty = true;
  80698. this._meshesWithPoseMatrix = new Array();
  80699. this._identity = BABYLON.Matrix.Identity();
  80700. this._ranges = {};
  80701. this._lastAbsoluteTransformsUpdateId = -1;
  80702. /**
  80703. * Specifies if the skeleton should be serialized
  80704. */
  80705. this.doNotSerialize = false;
  80706. this._animationPropertiesOverride = null;
  80707. // Events
  80708. /**
  80709. * An observable triggered before computing the skeleton's matrices
  80710. */
  80711. this.onBeforeComputeObservable = new BABYLON.Observable();
  80712. this.bones = [];
  80713. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80714. scene.skeletons.push(this);
  80715. //make sure it will recalculate the matrix next time prepare is called.
  80716. this._isDirty = true;
  80717. }
  80718. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  80719. /**
  80720. * Gets or sets the animation properties override
  80721. */
  80722. get: function () {
  80723. if (!this._animationPropertiesOverride) {
  80724. return this._scene.animationPropertiesOverride;
  80725. }
  80726. return this._animationPropertiesOverride;
  80727. },
  80728. set: function (value) {
  80729. this._animationPropertiesOverride = value;
  80730. },
  80731. enumerable: true,
  80732. configurable: true
  80733. });
  80734. // Members
  80735. /**
  80736. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  80737. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  80738. * @returns a Float32Array containing matrices data
  80739. */
  80740. Skeleton.prototype.getTransformMatrices = function (mesh) {
  80741. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  80742. return mesh._bonesTransformMatrices;
  80743. }
  80744. if (!this._transformMatrices) {
  80745. this.prepare();
  80746. }
  80747. return this._transformMatrices;
  80748. };
  80749. /**
  80750. * Gets the current hosting scene
  80751. * @returns a scene object
  80752. */
  80753. Skeleton.prototype.getScene = function () {
  80754. return this._scene;
  80755. };
  80756. // Methods
  80757. /**
  80758. * Gets a string representing the current skeleton data
  80759. * @param fullDetails defines a boolean indicating if we want a verbose version
  80760. * @returns a string representing the current skeleton data
  80761. */
  80762. Skeleton.prototype.toString = function (fullDetails) {
  80763. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  80764. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  80765. if (fullDetails) {
  80766. ret += ", Ranges: {";
  80767. var first = true;
  80768. for (var name_1 in this._ranges) {
  80769. if (first) {
  80770. ret += ", ";
  80771. first = false;
  80772. }
  80773. ret += name_1;
  80774. }
  80775. ret += "}";
  80776. }
  80777. return ret;
  80778. };
  80779. /**
  80780. * Get bone's index searching by name
  80781. * @param name defines bone's name to search for
  80782. * @return the indice of the bone. Returns -1 if not found
  80783. */
  80784. Skeleton.prototype.getBoneIndexByName = function (name) {
  80785. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  80786. if (this.bones[boneIndex].name === name) {
  80787. return boneIndex;
  80788. }
  80789. }
  80790. return -1;
  80791. };
  80792. /**
  80793. * Creater a new animation range
  80794. * @param name defines the name of the range
  80795. * @param from defines the start key
  80796. * @param to defines the end key
  80797. */
  80798. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  80799. // check name not already in use
  80800. if (!this._ranges[name]) {
  80801. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  80802. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80803. if (this.bones[i].animations[0]) {
  80804. this.bones[i].animations[0].createRange(name, from, to);
  80805. }
  80806. }
  80807. }
  80808. };
  80809. /**
  80810. * Delete a specific animation range
  80811. * @param name defines the name of the range
  80812. * @param deleteFrames defines if frames must be removed as well
  80813. */
  80814. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  80815. if (deleteFrames === void 0) { deleteFrames = true; }
  80816. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80817. if (this.bones[i].animations[0]) {
  80818. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  80819. }
  80820. }
  80821. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  80822. };
  80823. /**
  80824. * Gets a specific animation range
  80825. * @param name defines the name of the range to look for
  80826. * @returns the requested animation range or null if not found
  80827. */
  80828. Skeleton.prototype.getAnimationRange = function (name) {
  80829. return this._ranges[name];
  80830. };
  80831. /**
  80832. * Gets the list of all animation ranges defined on this skeleton
  80833. * @returns an array
  80834. */
  80835. Skeleton.prototype.getAnimationRanges = function () {
  80836. var animationRanges = [];
  80837. var name;
  80838. var i = 0;
  80839. for (name in this._ranges) {
  80840. animationRanges[i] = this._ranges[name];
  80841. i++;
  80842. }
  80843. return animationRanges;
  80844. };
  80845. /**
  80846. * Copy animation range from a source skeleton.
  80847. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  80848. * @param source defines the source skeleton
  80849. * @param name defines the name of the range to copy
  80850. * @param rescaleAsRequired defines if rescaling must be applied if required
  80851. * @returns true if operation was successful
  80852. */
  80853. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  80854. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  80855. if (this._ranges[name] || !source.getAnimationRange(name)) {
  80856. return false;
  80857. }
  80858. var ret = true;
  80859. var frameOffset = this._getHighestAnimationFrame() + 1;
  80860. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  80861. var boneDict = {};
  80862. var sourceBones = source.bones;
  80863. var nBones;
  80864. var i;
  80865. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  80866. boneDict[sourceBones[i].name] = sourceBones[i];
  80867. }
  80868. if (this.bones.length !== sourceBones.length) {
  80869. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  80870. ret = false;
  80871. }
  80872. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  80873. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  80874. var boneName = this.bones[i].name;
  80875. var sourceBone = boneDict[boneName];
  80876. if (sourceBone) {
  80877. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  80878. }
  80879. else {
  80880. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  80881. ret = false;
  80882. }
  80883. }
  80884. // do not call createAnimationRange(), since it also is done to bones, which was already done
  80885. var range = source.getAnimationRange(name);
  80886. if (range) {
  80887. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  80888. }
  80889. return ret;
  80890. };
  80891. /**
  80892. * Forces the skeleton to go to rest pose
  80893. */
  80894. Skeleton.prototype.returnToRest = function () {
  80895. for (var index = 0; index < this.bones.length; index++) {
  80896. this.bones[index].returnToRest();
  80897. }
  80898. };
  80899. Skeleton.prototype._getHighestAnimationFrame = function () {
  80900. var ret = 0;
  80901. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80902. if (this.bones[i].animations[0]) {
  80903. var highest = this.bones[i].animations[0].getHighestFrame();
  80904. if (ret < highest) {
  80905. ret = highest;
  80906. }
  80907. }
  80908. }
  80909. return ret;
  80910. };
  80911. /**
  80912. * Begin a specific animation range
  80913. * @param name defines the name of the range to start
  80914. * @param loop defines if looping must be turned on (false by default)
  80915. * @param speedRatio defines the speed ratio to apply (1 by default)
  80916. * @param onAnimationEnd defines a callback which will be called when animation will end
  80917. * @returns a new animatable
  80918. */
  80919. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  80920. var range = this.getAnimationRange(name);
  80921. if (!range) {
  80922. return null;
  80923. }
  80924. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  80925. };
  80926. /** @hidden */
  80927. Skeleton.prototype._markAsDirty = function () {
  80928. this._isDirty = true;
  80929. };
  80930. /** @hidden */
  80931. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  80932. this._meshesWithPoseMatrix.push(mesh);
  80933. };
  80934. /** @hidden */
  80935. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  80936. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  80937. if (index > -1) {
  80938. this._meshesWithPoseMatrix.splice(index, 1);
  80939. }
  80940. };
  80941. /** @hidden */
  80942. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  80943. this.onBeforeComputeObservable.notifyObservers(this);
  80944. for (var index = 0; index < this.bones.length; index++) {
  80945. var bone = this.bones[index];
  80946. var parentBone = bone.getParent();
  80947. if (parentBone) {
  80948. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  80949. }
  80950. else {
  80951. if (initialSkinMatrix) {
  80952. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  80953. }
  80954. else {
  80955. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  80956. }
  80957. }
  80958. if (bone._index !== -1) {
  80959. var mappedIndex = bone._index === null ? index : bone._index;
  80960. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  80961. }
  80962. }
  80963. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  80964. };
  80965. /**
  80966. * Build all resources required to render a skeleton
  80967. */
  80968. Skeleton.prototype.prepare = function () {
  80969. if (!this._isDirty) {
  80970. return;
  80971. }
  80972. if (this.needInitialSkinMatrix) {
  80973. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  80974. var mesh = this._meshesWithPoseMatrix[index];
  80975. var poseMatrix = mesh.getPoseMatrix();
  80976. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  80977. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80978. }
  80979. if (this._synchronizedWithMesh !== mesh) {
  80980. this._synchronizedWithMesh = mesh;
  80981. // Prepare bones
  80982. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  80983. var bone = this.bones[boneIndex];
  80984. if (!bone.getParent()) {
  80985. var matrix = bone.getBaseMatrix();
  80986. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  80987. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  80988. }
  80989. }
  80990. }
  80991. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  80992. }
  80993. }
  80994. else {
  80995. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  80996. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80997. }
  80998. this._computeTransformMatrices(this._transformMatrices, null);
  80999. }
  81000. this._isDirty = false;
  81001. this._scene._activeBones.addCount(this.bones.length, false);
  81002. };
  81003. /**
  81004. * Gets the list of animatables currently running for this skeleton
  81005. * @returns an array of animatables
  81006. */
  81007. Skeleton.prototype.getAnimatables = function () {
  81008. if (!this._animatables || this._animatables.length !== this.bones.length) {
  81009. this._animatables = [];
  81010. for (var index = 0; index < this.bones.length; index++) {
  81011. this._animatables.push(this.bones[index]);
  81012. }
  81013. }
  81014. return this._animatables;
  81015. };
  81016. /**
  81017. * Clone the current skeleton
  81018. * @param name defines the name of the new skeleton
  81019. * @param id defines the id of the enw skeleton
  81020. * @returns the new skeleton
  81021. */
  81022. Skeleton.prototype.clone = function (name, id) {
  81023. var result = new Skeleton(name, id || name, this._scene);
  81024. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81025. for (var index = 0; index < this.bones.length; index++) {
  81026. var source = this.bones[index];
  81027. var parentBone = null;
  81028. var parent_1 = source.getParent();
  81029. if (parent_1) {
  81030. var parentIndex = this.bones.indexOf(parent_1);
  81031. parentBone = result.bones[parentIndex];
  81032. }
  81033. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  81034. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  81035. }
  81036. if (this._ranges) {
  81037. result._ranges = {};
  81038. for (var rangeName in this._ranges) {
  81039. var range = this._ranges[rangeName];
  81040. if (range) {
  81041. result._ranges[rangeName] = range.clone();
  81042. }
  81043. }
  81044. }
  81045. this._isDirty = true;
  81046. return result;
  81047. };
  81048. /**
  81049. * Enable animation blending for this skeleton
  81050. * @param blendingSpeed defines the blending speed to apply
  81051. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  81052. */
  81053. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  81054. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  81055. this.bones.forEach(function (bone) {
  81056. bone.animations.forEach(function (animation) {
  81057. animation.enableBlending = true;
  81058. animation.blendingSpeed = blendingSpeed;
  81059. });
  81060. });
  81061. };
  81062. /**
  81063. * Releases all resources associated with the current skeleton
  81064. */
  81065. Skeleton.prototype.dispose = function () {
  81066. this._meshesWithPoseMatrix = [];
  81067. // Animations
  81068. this.getScene().stopAnimation(this);
  81069. // Remove from scene
  81070. this.getScene().removeSkeleton(this);
  81071. };
  81072. /**
  81073. * Serialize the skeleton in a JSON object
  81074. * @returns a JSON object
  81075. */
  81076. Skeleton.prototype.serialize = function () {
  81077. var serializationObject = {};
  81078. serializationObject.name = this.name;
  81079. serializationObject.id = this.id;
  81080. if (this.dimensionsAtRest) {
  81081. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  81082. }
  81083. serializationObject.bones = [];
  81084. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81085. for (var index = 0; index < this.bones.length; index++) {
  81086. var bone = this.bones[index];
  81087. var parent_2 = bone.getParent();
  81088. var serializedBone = {
  81089. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  81090. name: bone.name,
  81091. matrix: bone.getBaseMatrix().toArray(),
  81092. rest: bone.getRestPose().toArray()
  81093. };
  81094. serializationObject.bones.push(serializedBone);
  81095. if (bone.length) {
  81096. serializedBone.length = bone.length;
  81097. }
  81098. if (bone.metadata) {
  81099. serializedBone.metadata = bone.metadata;
  81100. }
  81101. if (bone.animations && bone.animations.length > 0) {
  81102. serializedBone.animation = bone.animations[0].serialize();
  81103. }
  81104. serializationObject.ranges = [];
  81105. for (var name in this._ranges) {
  81106. var source = this._ranges[name];
  81107. if (!source) {
  81108. continue;
  81109. }
  81110. var range = {};
  81111. range.name = name;
  81112. range.from = source.from;
  81113. range.to = source.to;
  81114. serializationObject.ranges.push(range);
  81115. }
  81116. }
  81117. return serializationObject;
  81118. };
  81119. /**
  81120. * Creates a new skeleton from serialized data
  81121. * @param parsedSkeleton defines the serialized data
  81122. * @param scene defines the hosting scene
  81123. * @returns a new skeleton
  81124. */
  81125. Skeleton.Parse = function (parsedSkeleton, scene) {
  81126. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  81127. if (parsedSkeleton.dimensionsAtRest) {
  81128. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  81129. }
  81130. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  81131. var index;
  81132. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  81133. var parsedBone = parsedSkeleton.bones[index];
  81134. var parentBone = null;
  81135. if (parsedBone.parentBoneIndex > -1) {
  81136. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  81137. }
  81138. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  81139. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  81140. if (parsedBone.length) {
  81141. bone.length = parsedBone.length;
  81142. }
  81143. if (parsedBone.metadata) {
  81144. bone.metadata = parsedBone.metadata;
  81145. }
  81146. if (parsedBone.animation) {
  81147. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  81148. }
  81149. }
  81150. // placed after bones, so createAnimationRange can cascade down
  81151. if (parsedSkeleton.ranges) {
  81152. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  81153. var data = parsedSkeleton.ranges[index];
  81154. skeleton.createAnimationRange(data.name, data.from, data.to);
  81155. }
  81156. }
  81157. return skeleton;
  81158. };
  81159. /**
  81160. * Compute all node absolute transforms
  81161. * @param forceUpdate defines if computation must be done even if cache is up to date
  81162. */
  81163. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  81164. if (forceUpdate === void 0) { forceUpdate = false; }
  81165. var renderId = this._scene.getRenderId();
  81166. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  81167. this.bones[0].computeAbsoluteTransforms();
  81168. this._lastAbsoluteTransformsUpdateId = renderId;
  81169. }
  81170. };
  81171. /**
  81172. * Gets the root pose matrix
  81173. * @returns a matrix
  81174. */
  81175. Skeleton.prototype.getPoseMatrix = function () {
  81176. var poseMatrix = null;
  81177. if (this._meshesWithPoseMatrix.length > 0) {
  81178. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  81179. }
  81180. return poseMatrix;
  81181. };
  81182. /**
  81183. * Sorts bones per internal index
  81184. */
  81185. Skeleton.prototype.sortBones = function () {
  81186. var bones = new Array();
  81187. var visited = new Array(this.bones.length);
  81188. for (var index = 0; index < this.bones.length; index++) {
  81189. this._sortBones(index, bones, visited);
  81190. }
  81191. this.bones = bones;
  81192. };
  81193. Skeleton.prototype._sortBones = function (index, bones, visited) {
  81194. if (visited[index]) {
  81195. return;
  81196. }
  81197. visited[index] = true;
  81198. var bone = this.bones[index];
  81199. if (bone._index === undefined) {
  81200. bone._index = index;
  81201. }
  81202. var parentBone = bone.getParent();
  81203. if (parentBone) {
  81204. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  81205. }
  81206. bones.push(bone);
  81207. };
  81208. return Skeleton;
  81209. }());
  81210. BABYLON.Skeleton = Skeleton;
  81211. })(BABYLON || (BABYLON = {}));
  81212. //# sourceMappingURL=babylon.skeleton.js.map
  81213. var BABYLON;
  81214. (function (BABYLON) {
  81215. var SphericalPolynomial = /** @class */ (function () {
  81216. function SphericalPolynomial() {
  81217. this.x = BABYLON.Vector3.Zero();
  81218. this.y = BABYLON.Vector3.Zero();
  81219. this.z = BABYLON.Vector3.Zero();
  81220. this.xx = BABYLON.Vector3.Zero();
  81221. this.yy = BABYLON.Vector3.Zero();
  81222. this.zz = BABYLON.Vector3.Zero();
  81223. this.xy = BABYLON.Vector3.Zero();
  81224. this.yz = BABYLON.Vector3.Zero();
  81225. this.zx = BABYLON.Vector3.Zero();
  81226. }
  81227. SphericalPolynomial.prototype.addAmbient = function (color) {
  81228. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81229. this.xx = this.xx.add(colorVector);
  81230. this.yy = this.yy.add(colorVector);
  81231. this.zz = this.zz.add(colorVector);
  81232. };
  81233. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  81234. var result = new SphericalPolynomial();
  81235. result.x = harmonics.L11.scale(1.02333);
  81236. result.y = harmonics.L1_1.scale(1.02333);
  81237. result.z = harmonics.L10.scale(1.02333);
  81238. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  81239. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  81240. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  81241. result.yz = harmonics.L2_1.scale(0.858086);
  81242. result.zx = harmonics.L21.scale(0.858086);
  81243. result.xy = harmonics.L2_2.scale(0.858086);
  81244. result.scale(1.0 / Math.PI);
  81245. return result;
  81246. };
  81247. SphericalPolynomial.prototype.scale = function (scale) {
  81248. this.x = this.x.scale(scale);
  81249. this.y = this.y.scale(scale);
  81250. this.z = this.z.scale(scale);
  81251. this.xx = this.xx.scale(scale);
  81252. this.yy = this.yy.scale(scale);
  81253. this.zz = this.zz.scale(scale);
  81254. this.yz = this.yz.scale(scale);
  81255. this.zx = this.zx.scale(scale);
  81256. this.xy = this.xy.scale(scale);
  81257. };
  81258. return SphericalPolynomial;
  81259. }());
  81260. BABYLON.SphericalPolynomial = SphericalPolynomial;
  81261. var SphericalHarmonics = /** @class */ (function () {
  81262. function SphericalHarmonics() {
  81263. this.L00 = BABYLON.Vector3.Zero();
  81264. this.L1_1 = BABYLON.Vector3.Zero();
  81265. this.L10 = BABYLON.Vector3.Zero();
  81266. this.L11 = BABYLON.Vector3.Zero();
  81267. this.L2_2 = BABYLON.Vector3.Zero();
  81268. this.L2_1 = BABYLON.Vector3.Zero();
  81269. this.L20 = BABYLON.Vector3.Zero();
  81270. this.L21 = BABYLON.Vector3.Zero();
  81271. this.L22 = BABYLON.Vector3.Zero();
  81272. }
  81273. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  81274. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81275. var c = colorVector.scale(deltaSolidAngle);
  81276. this.L00 = this.L00.add(c.scale(0.282095));
  81277. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  81278. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  81279. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  81280. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  81281. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  81282. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  81283. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  81284. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  81285. };
  81286. SphericalHarmonics.prototype.scale = function (scale) {
  81287. this.L00 = this.L00.scale(scale);
  81288. this.L1_1 = this.L1_1.scale(scale);
  81289. this.L10 = this.L10.scale(scale);
  81290. this.L11 = this.L11.scale(scale);
  81291. this.L2_2 = this.L2_2.scale(scale);
  81292. this.L2_1 = this.L2_1.scale(scale);
  81293. this.L20 = this.L20.scale(scale);
  81294. this.L21 = this.L21.scale(scale);
  81295. this.L22 = this.L22.scale(scale);
  81296. };
  81297. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  81298. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  81299. //
  81300. // E_lm = A_l * L_lm
  81301. //
  81302. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  81303. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  81304. // the scaling factors are given in equation 9.
  81305. // Constant (Band 0)
  81306. this.L00 = this.L00.scale(3.141593);
  81307. // Linear (Band 1)
  81308. this.L1_1 = this.L1_1.scale(2.094395);
  81309. this.L10 = this.L10.scale(2.094395);
  81310. this.L11 = this.L11.scale(2.094395);
  81311. // Quadratic (Band 2)
  81312. this.L2_2 = this.L2_2.scale(0.785398);
  81313. this.L2_1 = this.L2_1.scale(0.785398);
  81314. this.L20 = this.L20.scale(0.785398);
  81315. this.L21 = this.L21.scale(0.785398);
  81316. this.L22 = this.L22.scale(0.785398);
  81317. };
  81318. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  81319. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81320. // L = (1/pi) * E * rho
  81321. //
  81322. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81323. this.scale(1.0 / Math.PI);
  81324. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81325. // (The pixel shader must apply albedo after texture fetches, etc).
  81326. };
  81327. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  81328. var result = new SphericalHarmonics();
  81329. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  81330. result.L1_1 = polynomial.y.scale(0.977204);
  81331. result.L10 = polynomial.z.scale(0.977204);
  81332. result.L11 = polynomial.x.scale(0.977204);
  81333. result.L2_2 = polynomial.xy.scale(1.16538);
  81334. result.L2_1 = polynomial.yz.scale(1.16538);
  81335. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  81336. result.L21 = polynomial.zx.scale(1.16538);
  81337. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  81338. result.scale(Math.PI);
  81339. return result;
  81340. };
  81341. return SphericalHarmonics;
  81342. }());
  81343. BABYLON.SphericalHarmonics = SphericalHarmonics;
  81344. })(BABYLON || (BABYLON = {}));
  81345. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  81346. var BABYLON;
  81347. (function (BABYLON) {
  81348. var FileFaceOrientation = /** @class */ (function () {
  81349. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  81350. this.name = name;
  81351. this.worldAxisForNormal = worldAxisForNormal;
  81352. this.worldAxisForFileX = worldAxisForFileX;
  81353. this.worldAxisForFileY = worldAxisForFileY;
  81354. }
  81355. return FileFaceOrientation;
  81356. }());
  81357. ;
  81358. /**
  81359. * Helper class dealing with the extraction of spherical polynomial dataArray
  81360. * from a cube map.
  81361. */
  81362. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  81363. function CubeMapToSphericalPolynomialTools() {
  81364. }
  81365. /**
  81366. * Converts a texture to the according Spherical Polynomial data.
  81367. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81368. *
  81369. * @param texture The texture to extract the information from.
  81370. * @return The Spherical Polynomial data.
  81371. */
  81372. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  81373. if (!texture.isCube) {
  81374. // Only supports cube Textures currently.
  81375. return null;
  81376. }
  81377. var size = texture.getSize().width;
  81378. var right = texture.readPixels(0);
  81379. var left = texture.readPixels(1);
  81380. var up;
  81381. var down;
  81382. if (texture.isRenderTarget) {
  81383. up = texture.readPixels(3);
  81384. down = texture.readPixels(2);
  81385. }
  81386. else {
  81387. up = texture.readPixels(2);
  81388. down = texture.readPixels(3);
  81389. }
  81390. var front = texture.readPixels(4);
  81391. var back = texture.readPixels(5);
  81392. var gammaSpace = texture.gammaSpace;
  81393. // Always read as RGBA.
  81394. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81395. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81396. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81397. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81398. }
  81399. var cubeInfo = {
  81400. size: size,
  81401. right: right,
  81402. left: left,
  81403. up: up,
  81404. down: down,
  81405. front: front,
  81406. back: back,
  81407. format: format,
  81408. type: type,
  81409. gammaSpace: gammaSpace,
  81410. };
  81411. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  81412. };
  81413. /**
  81414. * Converts a cubemap to the according Spherical Polynomial data.
  81415. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81416. *
  81417. * @param cubeInfo The Cube map to extract the information from.
  81418. * @return The Spherical Polynomial data.
  81419. */
  81420. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  81421. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  81422. var totalSolidAngle = 0.0;
  81423. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  81424. var du = 2.0 / cubeInfo.size;
  81425. var dv = du;
  81426. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  81427. var minUV = du * 0.5 - 1.0;
  81428. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  81429. var fileFace = this.FileFaces[faceIndex];
  81430. var dataArray = cubeInfo[fileFace.name];
  81431. var v = minUV;
  81432. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  81433. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  81434. // Because SP is still linear, so summation is fine in that basis.
  81435. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  81436. for (var y = 0; y < cubeInfo.size; y++) {
  81437. var u = minUV;
  81438. for (var x = 0; x < cubeInfo.size; x++) {
  81439. // World direction (not normalised)
  81440. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  81441. worldDirection.normalize();
  81442. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  81443. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  81444. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  81445. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  81446. // Handle Integer types.
  81447. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81448. r /= 255;
  81449. g /= 255;
  81450. b /= 255;
  81451. }
  81452. // Handle Gamma space textures.
  81453. if (cubeInfo.gammaSpace) {
  81454. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  81455. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  81456. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  81457. }
  81458. var color = new BABYLON.Color3(r, g, b);
  81459. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  81460. totalSolidAngle += deltaSolidAngle;
  81461. u += du;
  81462. }
  81463. v += dv;
  81464. }
  81465. }
  81466. // Solid angle for entire sphere is 4*pi
  81467. var sphereSolidAngle = 4.0 * Math.PI;
  81468. // Adjust the solid angle to allow for how many faces we processed.
  81469. var facesProcessed = 6.0;
  81470. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  81471. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  81472. // This is needed because the numerical integration over the cube uses a
  81473. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  81474. // and also to compensate for accumulative error due to float precision in the summation.
  81475. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  81476. sphericalHarmonics.scale(correctionFactor);
  81477. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  81478. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  81479. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  81480. };
  81481. CubeMapToSphericalPolynomialTools.FileFaces = [
  81482. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  81483. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  81484. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  81485. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  81486. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  81487. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  81488. ];
  81489. return CubeMapToSphericalPolynomialTools;
  81490. }());
  81491. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  81492. })(BABYLON || (BABYLON = {}));
  81493. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  81494. var BABYLON;
  81495. (function (BABYLON) {
  81496. /**
  81497. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  81498. */
  81499. var PanoramaToCubeMapTools = /** @class */ (function () {
  81500. function PanoramaToCubeMapTools() {
  81501. }
  81502. /**
  81503. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  81504. *
  81505. * @param float32Array The source data.
  81506. * @param inputWidth The width of the input panorama.
  81507. * @param inputhHeight The height of the input panorama.
  81508. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  81509. * @return The cubemap data
  81510. */
  81511. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  81512. if (!float32Array) {
  81513. throw "ConvertPanoramaToCubemap: input cannot be null";
  81514. }
  81515. if (float32Array.length != inputWidth * inputHeight * 3) {
  81516. throw "ConvertPanoramaToCubemap: input size is wrong";
  81517. }
  81518. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  81519. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  81520. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  81521. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  81522. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  81523. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  81524. return {
  81525. front: textureFront,
  81526. back: textureBack,
  81527. left: textureLeft,
  81528. right: textureRight,
  81529. up: textureUp,
  81530. down: textureDown,
  81531. size: size,
  81532. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  81533. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  81534. gammaSpace: false,
  81535. };
  81536. };
  81537. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  81538. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  81539. var textureArray = new Float32Array(buffer);
  81540. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  81541. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  81542. var dy = 1 / texSize;
  81543. var fy = 0;
  81544. for (var y = 0; y < texSize; y++) {
  81545. var xv1 = faceData[0];
  81546. var xv2 = faceData[2];
  81547. for (var x = 0; x < texSize; x++) {
  81548. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  81549. v.normalize();
  81550. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  81551. // 3 channels per pixels
  81552. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  81553. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  81554. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  81555. xv1 = xv1.add(rotDX1);
  81556. xv2 = xv2.add(rotDX2);
  81557. }
  81558. fy += dy;
  81559. }
  81560. return textureArray;
  81561. };
  81562. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  81563. var theta = Math.atan2(vDir.z, vDir.x);
  81564. var phi = Math.acos(vDir.y);
  81565. while (theta < -Math.PI)
  81566. theta += 2 * Math.PI;
  81567. while (theta > Math.PI)
  81568. theta -= 2 * Math.PI;
  81569. var dx = theta / Math.PI;
  81570. var dy = phi / Math.PI;
  81571. // recenter.
  81572. dx = dx * 0.5 + 0.5;
  81573. var px = Math.round(dx * inputWidth);
  81574. if (px < 0)
  81575. px = 0;
  81576. else if (px >= inputWidth)
  81577. px = inputWidth - 1;
  81578. var py = Math.round(dy * inputHeight);
  81579. if (py < 0)
  81580. py = 0;
  81581. else if (py >= inputHeight)
  81582. py = inputHeight - 1;
  81583. var inputY = (inputHeight - py - 1);
  81584. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  81585. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  81586. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  81587. return {
  81588. r: r,
  81589. g: g,
  81590. b: b
  81591. };
  81592. };
  81593. PanoramaToCubeMapTools.FACE_FRONT = [
  81594. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81595. new BABYLON.Vector3(1.0, -1.0, -1.0),
  81596. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  81597. new BABYLON.Vector3(1.0, 1.0, -1.0)
  81598. ];
  81599. PanoramaToCubeMapTools.FACE_BACK = [
  81600. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81601. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81602. new BABYLON.Vector3(1.0, 1.0, 1.0),
  81603. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  81604. ];
  81605. PanoramaToCubeMapTools.FACE_RIGHT = [
  81606. new BABYLON.Vector3(1.0, -1.0, -1.0),
  81607. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81608. new BABYLON.Vector3(1.0, 1.0, -1.0),
  81609. new BABYLON.Vector3(1.0, 1.0, 1.0)
  81610. ];
  81611. PanoramaToCubeMapTools.FACE_LEFT = [
  81612. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81613. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81614. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  81615. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  81616. ];
  81617. PanoramaToCubeMapTools.FACE_DOWN = [
  81618. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  81619. new BABYLON.Vector3(1.0, 1.0, -1.0),
  81620. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  81621. new BABYLON.Vector3(1.0, 1.0, 1.0)
  81622. ];
  81623. PanoramaToCubeMapTools.FACE_UP = [
  81624. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81625. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81626. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81627. new BABYLON.Vector3(1.0, -1.0, -1.0)
  81628. ];
  81629. return PanoramaToCubeMapTools;
  81630. }());
  81631. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  81632. })(BABYLON || (BABYLON = {}));
  81633. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  81634. var BABYLON;
  81635. (function (BABYLON) {
  81636. ;
  81637. /**
  81638. * This groups tools to convert HDR texture to native colors array.
  81639. */
  81640. var HDRTools = /** @class */ (function () {
  81641. function HDRTools() {
  81642. }
  81643. HDRTools.Ldexp = function (mantissa, exponent) {
  81644. if (exponent > 1023) {
  81645. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  81646. }
  81647. if (exponent < -1074) {
  81648. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  81649. }
  81650. return mantissa * Math.pow(2, exponent);
  81651. };
  81652. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  81653. if (exponent > 0) { /*nonzero pixel*/
  81654. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  81655. float32array[index + 0] = red * exponent;
  81656. float32array[index + 1] = green * exponent;
  81657. float32array[index + 2] = blue * exponent;
  81658. }
  81659. else {
  81660. float32array[index + 0] = 0;
  81661. float32array[index + 1] = 0;
  81662. float32array[index + 2] = 0;
  81663. }
  81664. };
  81665. HDRTools.readStringLine = function (uint8array, startIndex) {
  81666. var line = "";
  81667. var character = "";
  81668. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  81669. character = String.fromCharCode(uint8array[i]);
  81670. if (character == "\n") {
  81671. break;
  81672. }
  81673. line += character;
  81674. }
  81675. return line;
  81676. };
  81677. /**
  81678. * Reads header information from an RGBE texture stored in a native array.
  81679. * More information on this format are available here:
  81680. * https://en.wikipedia.org/wiki/RGBE_image_format
  81681. *
  81682. * @param uint8array The binary file stored in native array.
  81683. * @return The header information.
  81684. */
  81685. HDRTools.RGBE_ReadHeader = function (uint8array) {
  81686. var height = 0;
  81687. var width = 0;
  81688. var line = this.readStringLine(uint8array, 0);
  81689. if (line[0] != '#' || line[1] != '?') {
  81690. throw "Bad HDR Format.";
  81691. }
  81692. var endOfHeader = false;
  81693. var findFormat = false;
  81694. var lineIndex = 0;
  81695. do {
  81696. lineIndex += (line.length + 1);
  81697. line = this.readStringLine(uint8array, lineIndex);
  81698. if (line == "FORMAT=32-bit_rle_rgbe") {
  81699. findFormat = true;
  81700. }
  81701. else if (line.length == 0) {
  81702. endOfHeader = true;
  81703. }
  81704. } while (!endOfHeader);
  81705. if (!findFormat) {
  81706. throw "HDR Bad header format, unsupported FORMAT";
  81707. }
  81708. lineIndex += (line.length + 1);
  81709. line = this.readStringLine(uint8array, lineIndex);
  81710. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  81711. var match = sizeRegexp.exec(line);
  81712. // TODO. Support +Y and -X if needed.
  81713. if (!match || match.length < 3) {
  81714. throw "HDR Bad header format, no size";
  81715. }
  81716. width = parseInt(match[2]);
  81717. height = parseInt(match[1]);
  81718. if (width < 8 || width > 0x7fff) {
  81719. throw "HDR Bad header format, unsupported size";
  81720. }
  81721. lineIndex += (line.length + 1);
  81722. return {
  81723. height: height,
  81724. width: width,
  81725. dataPosition: lineIndex
  81726. };
  81727. };
  81728. /**
  81729. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  81730. * This RGBE texture needs to store the information as a panorama.
  81731. *
  81732. * More information on this format are available here:
  81733. * https://en.wikipedia.org/wiki/RGBE_image_format
  81734. *
  81735. * @param buffer The binary file stored in an array buffer.
  81736. * @param size The expected size of the extracted cubemap.
  81737. * @return The Cube Map information.
  81738. */
  81739. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  81740. var uint8array = new Uint8Array(buffer);
  81741. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  81742. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81743. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  81744. return cubeMapData;
  81745. };
  81746. /**
  81747. * Returns the pixels data extracted from an RGBE texture.
  81748. * This pixels will be stored left to right up to down in the R G B order in one array.
  81749. *
  81750. * More information on this format are available here:
  81751. * https://en.wikipedia.org/wiki/RGBE_image_format
  81752. *
  81753. * @param uint8array The binary file stored in an array buffer.
  81754. * @param hdrInfo The header information of the file.
  81755. * @return The pixels data in RGB right to left up to down order.
  81756. */
  81757. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  81758. // Keep for multi format supports.
  81759. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81760. };
  81761. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  81762. var num_scanlines = hdrInfo.height;
  81763. var scanline_width = hdrInfo.width;
  81764. var a, b, c, d, count;
  81765. var dataIndex = hdrInfo.dataPosition;
  81766. var index = 0, endIndex = 0, i = 0;
  81767. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  81768. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  81769. // 3 channels of 4 bytes per pixel in float.
  81770. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  81771. var resultArray = new Float32Array(resultBuffer);
  81772. // read in each successive scanline
  81773. while (num_scanlines > 0) {
  81774. a = uint8array[dataIndex++];
  81775. b = uint8array[dataIndex++];
  81776. c = uint8array[dataIndex++];
  81777. d = uint8array[dataIndex++];
  81778. if (a != 2 || b != 2 || (c & 0x80)) {
  81779. // this file is not run length encoded
  81780. throw "HDR Bad header format, not RLE";
  81781. }
  81782. if (((c << 8) | d) != scanline_width) {
  81783. throw "HDR Bad header format, wrong scan line width";
  81784. }
  81785. index = 0;
  81786. // read each of the four channels for the scanline into the buffer
  81787. for (i = 0; i < 4; i++) {
  81788. endIndex = (i + 1) * scanline_width;
  81789. while (index < endIndex) {
  81790. a = uint8array[dataIndex++];
  81791. b = uint8array[dataIndex++];
  81792. if (a > 128) {
  81793. // a run of the same value
  81794. count = a - 128;
  81795. if ((count == 0) || (count > endIndex - index)) {
  81796. throw "HDR Bad Format, bad scanline data (run)";
  81797. }
  81798. while (count-- > 0) {
  81799. scanLineArray[index++] = b;
  81800. }
  81801. }
  81802. else {
  81803. // a non-run
  81804. count = a;
  81805. if ((count == 0) || (count > endIndex - index)) {
  81806. throw "HDR Bad Format, bad scanline data (non-run)";
  81807. }
  81808. scanLineArray[index++] = b;
  81809. if (--count > 0) {
  81810. for (var j = 0; j < count; j++) {
  81811. scanLineArray[index++] = uint8array[dataIndex++];
  81812. }
  81813. }
  81814. }
  81815. }
  81816. }
  81817. // now convert data from buffer into floats
  81818. for (i = 0; i < scanline_width; i++) {
  81819. a = scanLineArray[i];
  81820. b = scanLineArray[i + scanline_width];
  81821. c = scanLineArray[i + 2 * scanline_width];
  81822. d = scanLineArray[i + 3 * scanline_width];
  81823. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  81824. }
  81825. num_scanlines--;
  81826. }
  81827. return resultArray;
  81828. };
  81829. return HDRTools;
  81830. }());
  81831. BABYLON.HDRTools = HDRTools;
  81832. })(BABYLON || (BABYLON = {}));
  81833. //# sourceMappingURL=babylon.hdr.js.map
  81834. var BABYLON;
  81835. (function (BABYLON) {
  81836. /**
  81837. * Sets of helpers addressing the serialization and deserialization of environment texture
  81838. * stored in a BabylonJS env file.
  81839. * Those files are usually stored as .env files.
  81840. */
  81841. var EnvironmentTextureTools = /** @class */ (function () {
  81842. function EnvironmentTextureTools() {
  81843. }
  81844. /**
  81845. * Gets the environment info from an env file.
  81846. * @param data The array buffer containing the .env bytes.
  81847. * @returns the environment file info (the json header) if successfully parsed.
  81848. */
  81849. EnvironmentTextureTools.GetEnvInfo = function (data) {
  81850. var dataView = new DataView(data);
  81851. var pos = 0;
  81852. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81853. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  81854. BABYLON.Tools.Error('Not a babylon environment map');
  81855. return null;
  81856. }
  81857. }
  81858. // Read json manifest - collect characters up to null terminator
  81859. var manifestString = '';
  81860. var charCode = 0x00;
  81861. while ((charCode = dataView.getUint8(pos++))) {
  81862. manifestString += String.fromCharCode(charCode);
  81863. }
  81864. var manifest = JSON.parse(manifestString);
  81865. if (manifest.specular) {
  81866. // Extend the header with the position of the payload.
  81867. manifest.specular.specularDataPosition = pos;
  81868. }
  81869. return manifest;
  81870. };
  81871. /**
  81872. * Creates an environment texture from a loaded cube texture.
  81873. * @param texture defines the cube texture to convert in env file
  81874. * @return a promise containing the environment data if succesfull.
  81875. */
  81876. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  81877. var _this = this;
  81878. var internalTexture = texture.getInternalTexture();
  81879. if (!internalTexture) {
  81880. return Promise.reject("The cube texture is invalid.");
  81881. }
  81882. if (!texture._prefiltered) {
  81883. return Promise.reject("The cube texture is invalid (not prefiltered).");
  81884. }
  81885. var engine = internalTexture.getEngine();
  81886. if (engine && engine.premultipliedAlpha) {
  81887. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  81888. }
  81889. var canvas = engine.getRenderingCanvas();
  81890. if (!canvas) {
  81891. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  81892. }
  81893. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81894. if (!engine.getCaps().textureFloatRender) {
  81895. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81896. if (!engine.getCaps().textureHalfFloatRender) {
  81897. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  81898. }
  81899. }
  81900. var cubeWidth = internalTexture.width;
  81901. var hostingScene = new BABYLON.Scene(engine);
  81902. var specularTextures = {};
  81903. var promises = [];
  81904. // Read and collect all mipmaps data from the cube.
  81905. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  81906. mipmapsCount = Math.round(mipmapsCount);
  81907. var _loop_1 = function (i) {
  81908. var faceWidth = Math.pow(2, mipmapsCount - i);
  81909. var _loop_2 = function (face) {
  81910. var data = texture.readPixels(face, i);
  81911. // Creates a temp texture with the face data.
  81912. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  81913. // And rgbdEncode them.
  81914. var promise = new Promise(function (resolve, reject) {
  81915. 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);
  81916. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81917. rgbdPostProcess.onApply = function (effect) {
  81918. effect._bindTexture("textureSampler", tempTexture);
  81919. };
  81920. // As the process needs to happen on the main canvas, keep track of the current size
  81921. var currentW = engine.getRenderWidth();
  81922. var currentH = engine.getRenderHeight();
  81923. // Set the desired size for the texture
  81924. engine.setSize(faceWidth, faceWidth);
  81925. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  81926. // Reading datas from WebGL
  81927. canvas.toBlob(function (blob) {
  81928. var fileReader = new FileReader();
  81929. fileReader.onload = function (event) {
  81930. var arrayBuffer = event.target.result;
  81931. specularTextures[i * 6 + face] = arrayBuffer;
  81932. resolve();
  81933. };
  81934. fileReader.readAsArrayBuffer(blob);
  81935. });
  81936. // Reapply the previous canvas size
  81937. engine.setSize(currentW, currentH);
  81938. });
  81939. });
  81940. promises.push(promise);
  81941. };
  81942. // All faces of the cube.
  81943. for (var face = 0; face < 6; face++) {
  81944. _loop_2(face);
  81945. }
  81946. };
  81947. for (var i = 0; i <= mipmapsCount; i++) {
  81948. _loop_1(i);
  81949. }
  81950. // Once all the textures haves been collected as RGBD stored in PNGs
  81951. return Promise.all(promises).then(function () {
  81952. // We can delete the hosting scene keeping track of all the creation objects
  81953. hostingScene.dispose();
  81954. // Creates the json header for the env texture
  81955. var info = {
  81956. version: 1,
  81957. width: cubeWidth,
  81958. irradiance: _this._CreateEnvTextureIrradiance(texture),
  81959. specular: {
  81960. mipmaps: []
  81961. }
  81962. };
  81963. // Sets the specular image data information
  81964. var position = 0;
  81965. for (var i = 0; i <= mipmapsCount; i++) {
  81966. for (var face = 0; face < 6; face++) {
  81967. var byteLength = specularTextures[i * 6 + face].byteLength;
  81968. info.specular.mipmaps.push({
  81969. length: byteLength,
  81970. position: position
  81971. });
  81972. position += byteLength;
  81973. }
  81974. }
  81975. // Encode the JSON as an array buffer
  81976. var infoString = JSON.stringify(info);
  81977. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  81978. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  81979. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  81980. infoView[i] = infoString.charCodeAt(i);
  81981. }
  81982. // Ends up with a null terminator for easier parsing
  81983. infoView[infoString.length] = 0x00;
  81984. // Computes the final required size and creates the storage
  81985. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  81986. var finalBuffer = new ArrayBuffer(totalSize);
  81987. var finalBufferView = new Uint8Array(finalBuffer);
  81988. var dataView = new DataView(finalBuffer);
  81989. // Copy the magic bytes identifying the file in
  81990. var pos = 0;
  81991. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81992. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  81993. }
  81994. // Add the json info
  81995. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  81996. pos += infoBuffer.byteLength;
  81997. // Finally inserts the texture data
  81998. for (var i = 0; i <= mipmapsCount; i++) {
  81999. for (var face = 0; face < 6; face++) {
  82000. var dataBuffer = specularTextures[i * 6 + face];
  82001. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  82002. pos += dataBuffer.byteLength;
  82003. }
  82004. }
  82005. // Voila
  82006. return finalBuffer;
  82007. });
  82008. };
  82009. /**
  82010. * Creates a JSON representation of the spherical data.
  82011. * @param texture defines the texture containing the polynomials
  82012. * @return the JSON representation of the spherical info
  82013. */
  82014. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  82015. var polynmials = texture.sphericalPolynomial;
  82016. if (polynmials == null) {
  82017. return null;
  82018. }
  82019. return {
  82020. polynomials: true,
  82021. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  82022. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  82023. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  82024. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  82025. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  82026. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  82027. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  82028. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  82029. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  82030. };
  82031. };
  82032. /**
  82033. * Uploads the texture info contained in the env file to te GPU.
  82034. * @param texture defines the internal texture to upload to
  82035. * @param arrayBuffer defines the buffer cotaining the data to load
  82036. * @param info defines the texture info retrieved through the GetEnvInfo method
  82037. * @returns a promise
  82038. */
  82039. EnvironmentTextureTools.UploadLevelsAsync = function (texture, arrayBuffer, info) {
  82040. if (info.version !== 1) {
  82041. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82042. }
  82043. var specularInfo = info.specular;
  82044. if (!specularInfo) {
  82045. // Nothing else parsed so far
  82046. return Promise.resolve();
  82047. }
  82048. // Double checks the enclosed info
  82049. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  82050. mipmapsCount = Math.round(mipmapsCount) + 1;
  82051. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  82052. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  82053. }
  82054. // Gets everything ready.
  82055. var engine = texture.getEngine();
  82056. var expandTexture = false;
  82057. var generateNonLODTextures = false;
  82058. var rgbdPostProcess = null;
  82059. var cubeRtt = null;
  82060. var lodTextures = null;
  82061. var caps = engine.getCaps();
  82062. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82063. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82064. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  82065. // Add extra process if texture lod is not supported
  82066. if (!caps.textureLOD) {
  82067. expandTexture = false;
  82068. generateNonLODTextures = true;
  82069. lodTextures = {};
  82070. }
  82071. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  82072. else if (engine.webGLVersion < 2) {
  82073. expandTexture = false;
  82074. }
  82075. // If half float available we can uncompress the texture
  82076. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  82077. expandTexture = true;
  82078. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82079. }
  82080. // If full float available we can uncompress the texture
  82081. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  82082. expandTexture = true;
  82083. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82084. }
  82085. // Expand the texture if possible
  82086. if (expandTexture) {
  82087. // Simply run through the decode PP
  82088. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  82089. texture._isRGBD = false;
  82090. texture.invertY = false;
  82091. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  82092. generateDepthBuffer: false,
  82093. generateMipMaps: true,
  82094. generateStencilBuffer: false,
  82095. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  82096. type: texture.type,
  82097. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  82098. });
  82099. }
  82100. else {
  82101. texture._isRGBD = true;
  82102. texture.invertY = true;
  82103. // In case of missing support, applies the same patch than DDS files.
  82104. if (generateNonLODTextures) {
  82105. var mipSlices = 3;
  82106. var scale = texture._lodGenerationScale;
  82107. var offset = texture._lodGenerationOffset;
  82108. for (var i = 0; i < mipSlices; i++) {
  82109. //compute LOD from even spacing in smoothness (matching shader calculation)
  82110. var smoothness = i / (mipSlices - 1);
  82111. var roughness = 1 - smoothness;
  82112. var minLODIndex = offset; // roughness = 0
  82113. var maxLODIndex = BABYLON.Scalar.Log2(info.width) * scale + offset; // roughness = 1
  82114. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  82115. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  82116. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  82117. glTextureFromLod.isCube = true;
  82118. glTextureFromLod.invertY = true;
  82119. glTextureFromLod.generateMipMaps = false;
  82120. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  82121. // Wrap in a base texture for easy binding.
  82122. var lodTexture = new BABYLON.BaseTexture(null);
  82123. lodTexture.isCube = true;
  82124. lodTexture._texture = glTextureFromLod;
  82125. lodTextures[mipmapIndex] = lodTexture;
  82126. switch (i) {
  82127. case 0:
  82128. texture._lodTextureLow = lodTexture;
  82129. break;
  82130. case 1:
  82131. texture._lodTextureMid = lodTexture;
  82132. break;
  82133. case 2:
  82134. texture._lodTextureHigh = lodTexture;
  82135. break;
  82136. }
  82137. }
  82138. }
  82139. }
  82140. var promises = [];
  82141. var _loop_3 = function (i) {
  82142. var _loop_4 = function (face) {
  82143. // Retrieves the face data
  82144. var imageData = specularInfo.mipmaps[i * 6 + face];
  82145. var bytes = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageData.position, imageData.length);
  82146. // Constructs an image element from bytes
  82147. var blob = new Blob([bytes], { type: 'image/png' });
  82148. var url = URL.createObjectURL(blob);
  82149. var image = new Image();
  82150. image.src = url;
  82151. // Enqueue promise to upload to the texture.
  82152. var promise = new Promise(function (resolve, reject) {
  82153. ;
  82154. image.onload = function () {
  82155. if (expandTexture) {
  82156. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  82157. reject(message);
  82158. }, image);
  82159. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82160. // Uncompress the data to a RTT
  82161. rgbdPostProcess.onApply = function (effect) {
  82162. effect._bindTexture("textureSampler", tempTexture_1);
  82163. effect.setFloat2("scale", 1, 1);
  82164. };
  82165. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  82166. // Cleanup
  82167. engine.restoreDefaultFramebuffer();
  82168. tempTexture_1.dispose();
  82169. window.URL.revokeObjectURL(url);
  82170. resolve();
  82171. });
  82172. }
  82173. else {
  82174. engine._uploadImageToTexture(texture, face, i, image);
  82175. // Upload the face to the none lod texture support
  82176. if (generateNonLODTextures) {
  82177. var lodTexture = lodTextures[i];
  82178. if (lodTexture) {
  82179. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  82180. }
  82181. }
  82182. resolve();
  82183. }
  82184. };
  82185. image.onerror = function (error) {
  82186. reject(error);
  82187. };
  82188. });
  82189. promises.push(promise);
  82190. };
  82191. // All faces
  82192. for (var face = 0; face < 6; face++) {
  82193. _loop_4(face);
  82194. }
  82195. };
  82196. // All mipmaps
  82197. for (var i = 0; i < mipmapsCount; i++) {
  82198. _loop_3(i);
  82199. }
  82200. // Once all done, finishes the cleanup and return
  82201. return Promise.all(promises).then(function () {
  82202. // Relase temp RTT.
  82203. if (cubeRtt) {
  82204. engine._releaseFramebufferObjects(cubeRtt);
  82205. cubeRtt._swapAndDie(texture);
  82206. }
  82207. // Relase temp Post Process.
  82208. if (rgbdPostProcess) {
  82209. rgbdPostProcess.dispose();
  82210. }
  82211. // Flag internal texture as ready in case they are in use.
  82212. if (generateNonLODTextures) {
  82213. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  82214. texture._lodTextureHigh._texture.isReady = true;
  82215. }
  82216. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  82217. texture._lodTextureMid._texture.isReady = true;
  82218. }
  82219. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  82220. texture._lodTextureLow._texture.isReady = true;
  82221. }
  82222. }
  82223. });
  82224. };
  82225. /**
  82226. * Uploads spherical polynomials information to the texture.
  82227. * @param texture defines the texture we are trying to upload the information to
  82228. * @param arrayBuffer defines the array buffer holding the data
  82229. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  82230. */
  82231. EnvironmentTextureTools.UploadPolynomials = function (texture, arrayBuffer, info) {
  82232. if (info.version !== 1) {
  82233. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82234. }
  82235. var irradianceInfo = info.irradiance;
  82236. if (!irradianceInfo) {
  82237. return;
  82238. }
  82239. //harmonics now represent radiance
  82240. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  82241. if (irradianceInfo.polynomials) {
  82242. EnvironmentTextureTools._UploadSP(irradianceInfo, texture._sphericalPolynomial);
  82243. }
  82244. else {
  82245. // convert From SH to SP.
  82246. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance(irradianceInfo);
  82247. EnvironmentTextureTools._ConvertSHToSP(irradianceInfo, texture._sphericalPolynomial);
  82248. }
  82249. };
  82250. /**
  82251. * Upload spherical polynomial coefficients to the texture
  82252. * @param polynmials Spherical polynmial coefficients (9)
  82253. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  82254. */
  82255. EnvironmentTextureTools._UploadSP = function (polynmials, outPolynomialCoefficents) {
  82256. outPolynomialCoefficents.x.x = polynmials.x[0];
  82257. outPolynomialCoefficents.x.y = polynmials.x[1];
  82258. outPolynomialCoefficents.x.z = polynmials.x[2];
  82259. outPolynomialCoefficents.y.x = polynmials.y[0];
  82260. outPolynomialCoefficents.y.y = polynmials.y[1];
  82261. outPolynomialCoefficents.y.z = polynmials.y[2];
  82262. outPolynomialCoefficents.z.x = polynmials.z[0];
  82263. outPolynomialCoefficents.z.y = polynmials.z[1];
  82264. outPolynomialCoefficents.z.z = polynmials.z[2];
  82265. //xx
  82266. outPolynomialCoefficents.xx.x = polynmials.xx[0];
  82267. outPolynomialCoefficents.xx.y = polynmials.xx[1];
  82268. outPolynomialCoefficents.xx.z = polynmials.xx[2];
  82269. outPolynomialCoefficents.yy.x = polynmials.yy[0];
  82270. outPolynomialCoefficents.yy.y = polynmials.yy[1];
  82271. outPolynomialCoefficents.yy.z = polynmials.yy[2];
  82272. outPolynomialCoefficents.zz.x = polynmials.zz[0];
  82273. outPolynomialCoefficents.zz.y = polynmials.zz[1];
  82274. outPolynomialCoefficents.zz.z = polynmials.zz[2];
  82275. //yz
  82276. outPolynomialCoefficents.yz.x = polynmials.yz[0];
  82277. outPolynomialCoefficents.yz.y = polynmials.yz[1];
  82278. outPolynomialCoefficents.yz.z = polynmials.yz[2];
  82279. outPolynomialCoefficents.zx.x = polynmials.zx[0];
  82280. outPolynomialCoefficents.zx.y = polynmials.zx[1];
  82281. outPolynomialCoefficents.zx.z = polynmials.zx[2];
  82282. outPolynomialCoefficents.xy.x = polynmials.xy[0];
  82283. outPolynomialCoefficents.xy.y = polynmials.xy[1];
  82284. outPolynomialCoefficents.xy.z = polynmials.xy[2];
  82285. };
  82286. /**
  82287. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  82288. * L = (1/pi) * E * rho
  82289. *
  82290. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  82291. * @param harmonics Spherical harmonic coefficients (9)
  82292. */
  82293. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  82294. var scaleFactor = 1 / Math.PI;
  82295. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  82296. // (The pixel shader must apply albedo after texture fetches, etc).
  82297. harmonics.l00[0] *= scaleFactor;
  82298. harmonics.l00[1] *= scaleFactor;
  82299. harmonics.l00[2] *= scaleFactor;
  82300. harmonics.l1_1[0] *= scaleFactor;
  82301. harmonics.l1_1[1] *= scaleFactor;
  82302. harmonics.l1_1[2] *= scaleFactor;
  82303. harmonics.l10[0] *= scaleFactor;
  82304. harmonics.l10[1] *= scaleFactor;
  82305. harmonics.l10[2] *= scaleFactor;
  82306. harmonics.l11[0] *= scaleFactor;
  82307. harmonics.l11[1] *= scaleFactor;
  82308. harmonics.l11[2] *= scaleFactor;
  82309. harmonics.l2_2[0] *= scaleFactor;
  82310. harmonics.l2_2[1] *= scaleFactor;
  82311. harmonics.l2_2[2] *= scaleFactor;
  82312. harmonics.l2_1[0] *= scaleFactor;
  82313. harmonics.l2_1[1] *= scaleFactor;
  82314. harmonics.l2_1[2] *= scaleFactor;
  82315. harmonics.l20[0] *= scaleFactor;
  82316. harmonics.l20[1] *= scaleFactor;
  82317. harmonics.l20[2] *= scaleFactor;
  82318. harmonics.l21[0] *= scaleFactor;
  82319. harmonics.l21[1] *= scaleFactor;
  82320. harmonics.l21[2] *= scaleFactor;
  82321. harmonics.l22[0] *= scaleFactor;
  82322. harmonics.l22[1] *= scaleFactor;
  82323. harmonics.l22[2] *= scaleFactor;
  82324. };
  82325. /**
  82326. * Convert spherical harmonics to spherical polynomial coefficients
  82327. * @param harmonics Spherical harmonic coefficients (9)
  82328. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  82329. */
  82330. EnvironmentTextureTools._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  82331. var rPi = 1 / Math.PI;
  82332. //x
  82333. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  82334. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  82335. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  82336. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  82337. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  82338. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  82339. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  82340. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  82341. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  82342. //xx
  82343. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  82344. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  82345. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  82346. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  82347. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  82348. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  82349. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  82350. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  82351. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  82352. //yz
  82353. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  82354. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  82355. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  82356. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  82357. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  82358. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  82359. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  82360. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  82361. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  82362. };
  82363. /**
  82364. * Magic number identifying the env file.
  82365. */
  82366. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  82367. return EnvironmentTextureTools;
  82368. }());
  82369. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  82370. })(BABYLON || (BABYLON = {}));
  82371. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  82372. var BABYLON;
  82373. (function (BABYLON) {
  82374. /**
  82375. * This represents a texture coming from an HDR input.
  82376. *
  82377. * The only supported format is currently panorama picture stored in RGBE format.
  82378. * Example of such files can be found on HDRLib: http://hdrlib.com/
  82379. */
  82380. var HDRCubeTexture = /** @class */ (function (_super) {
  82381. __extends(HDRCubeTexture, _super);
  82382. /**
  82383. * Instantiates an HDRTexture from the following parameters.
  82384. *
  82385. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  82386. * @param scene The scene the texture will be used in
  82387. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  82388. * @param noMipmap Forces to not generate the mipmap if true
  82389. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  82390. * @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)
  82391. * @param reserved Reserved flag for internal use.
  82392. */
  82393. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  82394. if (noMipmap === void 0) { noMipmap = false; }
  82395. if (generateHarmonics === void 0) { generateHarmonics = true; }
  82396. if (gammaSpace === void 0) { gammaSpace = false; }
  82397. if (reserved === void 0) { reserved = false; }
  82398. if (onLoad === void 0) { onLoad = null; }
  82399. if (onError === void 0) { onError = null; }
  82400. var _this = _super.call(this, scene) || this;
  82401. _this._generateHarmonics = true;
  82402. _this._onLoad = null;
  82403. _this._onError = null;
  82404. /**
  82405. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  82406. */
  82407. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  82408. _this._isBlocking = true;
  82409. _this._rotationY = 0;
  82410. /**
  82411. * Gets or sets the center of the bounding box associated with the cube texture
  82412. * It must define where the camera used to render the texture was set
  82413. */
  82414. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  82415. if (!url) {
  82416. return _this;
  82417. }
  82418. _this.name = url;
  82419. _this.url = url;
  82420. _this.hasAlpha = false;
  82421. _this.isCube = true;
  82422. _this._textureMatrix = BABYLON.Matrix.Identity();
  82423. _this._onLoad = onLoad;
  82424. _this._onError = onError;
  82425. _this.gammaSpace = gammaSpace;
  82426. _this._noMipmap = noMipmap;
  82427. _this._size = size;
  82428. _this._texture = _this._getFromCache(url, _this._noMipmap);
  82429. if (!_this._texture) {
  82430. if (!scene.useDelayedTextureLoading) {
  82431. _this.loadTexture();
  82432. }
  82433. else {
  82434. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  82435. }
  82436. }
  82437. return _this;
  82438. }
  82439. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  82440. /**
  82441. * Gets wether or not the texture is blocking during loading.
  82442. */
  82443. get: function () {
  82444. return this._isBlocking;
  82445. },
  82446. /**
  82447. * Sets wether or not the texture is blocking during loading.
  82448. */
  82449. set: function (value) {
  82450. this._isBlocking = value;
  82451. },
  82452. enumerable: true,
  82453. configurable: true
  82454. });
  82455. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  82456. /**
  82457. * Gets texture matrix rotation angle around Y axis radians.
  82458. */
  82459. get: function () {
  82460. return this._rotationY;
  82461. },
  82462. /**
  82463. * Sets texture matrix rotation angle around Y axis in radians.
  82464. */
  82465. set: function (value) {
  82466. this._rotationY = value;
  82467. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  82468. },
  82469. enumerable: true,
  82470. configurable: true
  82471. });
  82472. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  82473. get: function () {
  82474. return this._boundingBoxSize;
  82475. },
  82476. /**
  82477. * Gets or sets the size of the bounding box associated with the cube texture
  82478. * When defined, the cubemap will switch to local mode
  82479. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  82480. * @example https://www.babylonjs-playground.com/#RNASML
  82481. */
  82482. set: function (value) {
  82483. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  82484. return;
  82485. }
  82486. this._boundingBoxSize = value;
  82487. var scene = this.getScene();
  82488. if (scene) {
  82489. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  82490. }
  82491. },
  82492. enumerable: true,
  82493. configurable: true
  82494. });
  82495. /**
  82496. * Occurs when the file is raw .hdr file.
  82497. */
  82498. HDRCubeTexture.prototype.loadTexture = function () {
  82499. var _this = this;
  82500. var callback = function (buffer) {
  82501. _this.lodGenerationOffset = 0.0;
  82502. _this.lodGenerationScale = 0.8;
  82503. var scene = _this.getScene();
  82504. if (!scene) {
  82505. return null;
  82506. }
  82507. // Extract the raw linear data.
  82508. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  82509. // Generate harmonics if needed.
  82510. if (_this._generateHarmonics) {
  82511. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  82512. _this.sphericalPolynomial = sphericalPolynomial;
  82513. }
  82514. var results = [];
  82515. var byteArray = null;
  82516. // Push each faces.
  82517. for (var j = 0; j < 6; j++) {
  82518. // Create uintarray fallback.
  82519. if (!scene.getEngine().getCaps().textureFloat) {
  82520. // 3 channels of 1 bytes per pixel in bytes.
  82521. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  82522. byteArray = new Uint8Array(byteBuffer);
  82523. }
  82524. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  82525. // If special cases.
  82526. if (_this.gammaSpace || byteArray) {
  82527. for (var i = 0; i < _this._size * _this._size; i++) {
  82528. // Put in gamma space if requested.
  82529. if (_this.gammaSpace) {
  82530. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  82531. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  82532. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  82533. }
  82534. // Convert to int texture for fallback.
  82535. if (byteArray) {
  82536. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  82537. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  82538. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  82539. // May use luminance instead if the result is not accurate.
  82540. var max = Math.max(Math.max(r, g), b);
  82541. if (max > 255) {
  82542. var scale = 255 / max;
  82543. r *= scale;
  82544. g *= scale;
  82545. b *= scale;
  82546. }
  82547. byteArray[(i * 3) + 0] = r;
  82548. byteArray[(i * 3) + 1] = g;
  82549. byteArray[(i * 3) + 2] = b;
  82550. }
  82551. }
  82552. }
  82553. if (byteArray) {
  82554. results.push(byteArray);
  82555. }
  82556. else {
  82557. results.push(dataFace);
  82558. }
  82559. }
  82560. return results;
  82561. };
  82562. var scene = this.getScene();
  82563. if (scene) {
  82564. 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);
  82565. }
  82566. };
  82567. HDRCubeTexture.prototype.clone = function () {
  82568. var scene = this.getScene();
  82569. if (!scene) {
  82570. return this;
  82571. }
  82572. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  82573. // Base texture
  82574. newTexture.level = this.level;
  82575. newTexture.wrapU = this.wrapU;
  82576. newTexture.wrapV = this.wrapV;
  82577. newTexture.coordinatesIndex = this.coordinatesIndex;
  82578. newTexture.coordinatesMode = this.coordinatesMode;
  82579. return newTexture;
  82580. };
  82581. // Methods
  82582. HDRCubeTexture.prototype.delayLoad = function () {
  82583. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  82584. return;
  82585. }
  82586. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  82587. this._texture = this._getFromCache(this.url, this._noMipmap);
  82588. if (!this._texture) {
  82589. this.loadTexture();
  82590. }
  82591. };
  82592. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  82593. return this._textureMatrix;
  82594. };
  82595. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  82596. this._textureMatrix = value;
  82597. };
  82598. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  82599. var texture = null;
  82600. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  82601. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  82602. texture.name = parsedTexture.name;
  82603. texture.hasAlpha = parsedTexture.hasAlpha;
  82604. texture.level = parsedTexture.level;
  82605. texture.coordinatesMode = parsedTexture.coordinatesMode;
  82606. texture.isBlocking = parsedTexture.isBlocking;
  82607. }
  82608. if (texture) {
  82609. if (parsedTexture.boundingBoxPosition) {
  82610. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  82611. }
  82612. if (parsedTexture.boundingBoxSize) {
  82613. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  82614. }
  82615. if (parsedTexture.rotationY) {
  82616. texture.rotationY = parsedTexture.rotationY;
  82617. }
  82618. }
  82619. return texture;
  82620. };
  82621. HDRCubeTexture.prototype.serialize = function () {
  82622. if (!this.name) {
  82623. return null;
  82624. }
  82625. var serializationObject = {};
  82626. serializationObject.name = this.name;
  82627. serializationObject.hasAlpha = this.hasAlpha;
  82628. serializationObject.isCube = true;
  82629. serializationObject.level = this.level;
  82630. serializationObject.size = this._size;
  82631. serializationObject.coordinatesMode = this.coordinatesMode;
  82632. serializationObject.useInGammaSpace = this.gammaSpace;
  82633. serializationObject.generateHarmonics = this._generateHarmonics;
  82634. serializationObject.customType = "BABYLON.HDRCubeTexture";
  82635. serializationObject.noMipmap = this._noMipmap;
  82636. serializationObject.isBlocking = this._isBlocking;
  82637. serializationObject.rotationY = this._rotationY;
  82638. return serializationObject;
  82639. };
  82640. HDRCubeTexture._facesMapping = [
  82641. "right",
  82642. "left",
  82643. "up",
  82644. "down",
  82645. "front",
  82646. "back"
  82647. ];
  82648. return HDRCubeTexture;
  82649. }(BABYLON.BaseTexture));
  82650. BABYLON.HDRCubeTexture = HDRCubeTexture;
  82651. })(BABYLON || (BABYLON = {}));
  82652. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  82653. var BABYLON;
  82654. (function (BABYLON) {
  82655. var IndexedVector2 = /** @class */ (function (_super) {
  82656. __extends(IndexedVector2, _super);
  82657. function IndexedVector2(original, index) {
  82658. var _this = _super.call(this, original.x, original.y) || this;
  82659. _this.index = index;
  82660. return _this;
  82661. }
  82662. return IndexedVector2;
  82663. }(BABYLON.Vector2));
  82664. var PolygonPoints = /** @class */ (function () {
  82665. function PolygonPoints() {
  82666. this.elements = new Array();
  82667. }
  82668. PolygonPoints.prototype.add = function (originalPoints) {
  82669. var _this = this;
  82670. var result = new Array();
  82671. originalPoints.forEach(function (point) {
  82672. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  82673. var newPoint = new IndexedVector2(point, _this.elements.length);
  82674. result.push(newPoint);
  82675. _this.elements.push(newPoint);
  82676. }
  82677. });
  82678. return result;
  82679. };
  82680. PolygonPoints.prototype.computeBounds = function () {
  82681. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82682. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82683. this.elements.forEach(function (point) {
  82684. // x
  82685. if (point.x < lmin.x) {
  82686. lmin.x = point.x;
  82687. }
  82688. else if (point.x > lmax.x) {
  82689. lmax.x = point.x;
  82690. }
  82691. // y
  82692. if (point.y < lmin.y) {
  82693. lmin.y = point.y;
  82694. }
  82695. else if (point.y > lmax.y) {
  82696. lmax.y = point.y;
  82697. }
  82698. });
  82699. return {
  82700. min: lmin,
  82701. max: lmax,
  82702. width: lmax.x - lmin.x,
  82703. height: lmax.y - lmin.y
  82704. };
  82705. };
  82706. return PolygonPoints;
  82707. }());
  82708. var Polygon = /** @class */ (function () {
  82709. function Polygon() {
  82710. }
  82711. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  82712. return [
  82713. new BABYLON.Vector2(xmin, ymin),
  82714. new BABYLON.Vector2(xmax, ymin),
  82715. new BABYLON.Vector2(xmax, ymax),
  82716. new BABYLON.Vector2(xmin, ymax)
  82717. ];
  82718. };
  82719. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  82720. if (cx === void 0) { cx = 0; }
  82721. if (cy === void 0) { cy = 0; }
  82722. if (numberOfSides === void 0) { numberOfSides = 32; }
  82723. var result = new Array();
  82724. var angle = 0;
  82725. var increment = (Math.PI * 2) / numberOfSides;
  82726. for (var i = 0; i < numberOfSides; i++) {
  82727. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  82728. angle -= increment;
  82729. }
  82730. return result;
  82731. };
  82732. Polygon.Parse = function (input) {
  82733. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  82734. var i, result = [];
  82735. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  82736. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  82737. }
  82738. return result;
  82739. };
  82740. Polygon.StartingAt = function (x, y) {
  82741. return BABYLON.Path2.StartingAt(x, y);
  82742. };
  82743. return Polygon;
  82744. }());
  82745. BABYLON.Polygon = Polygon;
  82746. var PolygonMeshBuilder = /** @class */ (function () {
  82747. function PolygonMeshBuilder(name, contours, scene) {
  82748. this._points = new PolygonPoints();
  82749. this._outlinepoints = new PolygonPoints();
  82750. this._holes = new Array();
  82751. this._epoints = new Array();
  82752. this._eholes = new Array();
  82753. this._name = name;
  82754. this._scene = scene;
  82755. var points;
  82756. if (contours instanceof BABYLON.Path2) {
  82757. points = contours.getPoints();
  82758. }
  82759. else {
  82760. points = contours;
  82761. }
  82762. this._addToepoint(points);
  82763. this._points.add(points);
  82764. this._outlinepoints.add(points);
  82765. if (typeof earcut === 'undefined') {
  82766. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  82767. }
  82768. }
  82769. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  82770. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  82771. var p = points_1[_i];
  82772. this._epoints.push(p.x, p.y);
  82773. }
  82774. };
  82775. PolygonMeshBuilder.prototype.addHole = function (hole) {
  82776. this._points.add(hole);
  82777. var holepoints = new PolygonPoints();
  82778. holepoints.add(hole);
  82779. this._holes.push(holepoints);
  82780. this._eholes.push(this._epoints.length / 2);
  82781. this._addToepoint(hole);
  82782. return this;
  82783. };
  82784. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  82785. var _this = this;
  82786. if (updatable === void 0) { updatable = false; }
  82787. if (depth === void 0) { depth = 0; }
  82788. var result = new BABYLON.Mesh(this._name, this._scene);
  82789. var normals = new Array();
  82790. var positions = new Array();
  82791. var uvs = new Array();
  82792. var bounds = this._points.computeBounds();
  82793. this._points.elements.forEach(function (p) {
  82794. normals.push(0, 1.0, 0);
  82795. positions.push(p.x, 0, p.y);
  82796. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  82797. });
  82798. var indices = new Array();
  82799. var res = earcut(this._epoints, this._eholes, 2);
  82800. for (var i = 0; i < res.length; i++) {
  82801. indices.push(res[i]);
  82802. }
  82803. if (depth > 0) {
  82804. var positionscount = (positions.length / 3); //get the current pointcount
  82805. this._points.elements.forEach(function (p) {
  82806. normals.push(0, -1.0, 0);
  82807. positions.push(p.x, -depth, p.y);
  82808. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  82809. });
  82810. var totalCount = indices.length;
  82811. for (var i = 0; i < totalCount; i += 3) {
  82812. var i0 = indices[i + 0];
  82813. var i1 = indices[i + 1];
  82814. var i2 = indices[i + 2];
  82815. indices.push(i2 + positionscount);
  82816. indices.push(i1 + positionscount);
  82817. indices.push(i0 + positionscount);
  82818. }
  82819. //Add the sides
  82820. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  82821. this._holes.forEach(function (hole) {
  82822. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  82823. });
  82824. }
  82825. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  82826. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  82827. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  82828. result.setIndices(indices);
  82829. return result;
  82830. };
  82831. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  82832. var StartIndex = positions.length / 3;
  82833. var ulength = 0;
  82834. for (var i = 0; i < points.elements.length; i++) {
  82835. var p = points.elements[i];
  82836. var p1;
  82837. if ((i + 1) > points.elements.length - 1) {
  82838. p1 = points.elements[0];
  82839. }
  82840. else {
  82841. p1 = points.elements[i + 1];
  82842. }
  82843. positions.push(p.x, 0, p.y);
  82844. positions.push(p.x, -depth, p.y);
  82845. positions.push(p1.x, 0, p1.y);
  82846. positions.push(p1.x, -depth, p1.y);
  82847. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  82848. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  82849. var v3 = v2.subtract(v1);
  82850. var v4 = new BABYLON.Vector3(0, 1, 0);
  82851. var vn = BABYLON.Vector3.Cross(v3, v4);
  82852. vn = vn.normalize();
  82853. uvs.push(ulength / bounds.width, 0);
  82854. uvs.push(ulength / bounds.width, 1);
  82855. ulength += v3.length();
  82856. uvs.push((ulength / bounds.width), 0);
  82857. uvs.push((ulength / bounds.width), 1);
  82858. if (!flip) {
  82859. normals.push(-vn.x, -vn.y, -vn.z);
  82860. normals.push(-vn.x, -vn.y, -vn.z);
  82861. normals.push(-vn.x, -vn.y, -vn.z);
  82862. normals.push(-vn.x, -vn.y, -vn.z);
  82863. indices.push(StartIndex);
  82864. indices.push(StartIndex + 1);
  82865. indices.push(StartIndex + 2);
  82866. indices.push(StartIndex + 1);
  82867. indices.push(StartIndex + 3);
  82868. indices.push(StartIndex + 2);
  82869. }
  82870. else {
  82871. normals.push(vn.x, vn.y, vn.z);
  82872. normals.push(vn.x, vn.y, vn.z);
  82873. normals.push(vn.x, vn.y, vn.z);
  82874. normals.push(vn.x, vn.y, vn.z);
  82875. indices.push(StartIndex);
  82876. indices.push(StartIndex + 2);
  82877. indices.push(StartIndex + 1);
  82878. indices.push(StartIndex + 1);
  82879. indices.push(StartIndex + 2);
  82880. indices.push(StartIndex + 3);
  82881. }
  82882. StartIndex += 4;
  82883. }
  82884. ;
  82885. };
  82886. return PolygonMeshBuilder;
  82887. }());
  82888. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  82889. })(BABYLON || (BABYLON = {}));
  82890. //# sourceMappingURL=babylon.polygonMesh.js.map
  82891. var BABYLON;
  82892. (function (BABYLON) {
  82893. // Unique ID when we import meshes from Babylon to CSG
  82894. var currentCSGMeshId = 0;
  82895. // # class Vertex
  82896. // Represents a vertex of a polygon. Use your own vertex class instead of this
  82897. // one to provide additional features like texture coordinates and vertex
  82898. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  82899. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  82900. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  82901. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  82902. // is not used anywhere else.
  82903. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  82904. var Vertex = /** @class */ (function () {
  82905. function Vertex(pos, normal, uv) {
  82906. this.pos = pos;
  82907. this.normal = normal;
  82908. this.uv = uv;
  82909. }
  82910. Vertex.prototype.clone = function () {
  82911. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  82912. };
  82913. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  82914. // orientation of a polygon is flipped.
  82915. Vertex.prototype.flip = function () {
  82916. this.normal = this.normal.scale(-1);
  82917. };
  82918. // Create a new vertex between this vertex and `other` by linearly
  82919. // interpolating all properties using a parameter of `t`. Subclasses should
  82920. // override this to interpolate additional properties.
  82921. Vertex.prototype.interpolate = function (other, t) {
  82922. 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));
  82923. };
  82924. return Vertex;
  82925. }());
  82926. // # class Plane
  82927. // Represents a plane in 3D space.
  82928. var Plane = /** @class */ (function () {
  82929. function Plane(normal, w) {
  82930. this.normal = normal;
  82931. this.w = w;
  82932. }
  82933. Plane.FromPoints = function (a, b, c) {
  82934. var v0 = c.subtract(a);
  82935. var v1 = b.subtract(a);
  82936. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  82937. return null;
  82938. }
  82939. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  82940. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  82941. };
  82942. Plane.prototype.clone = function () {
  82943. return new Plane(this.normal.clone(), this.w);
  82944. };
  82945. Plane.prototype.flip = function () {
  82946. this.normal.scaleInPlace(-1);
  82947. this.w = -this.w;
  82948. };
  82949. // Split `polygon` by this plane if needed, then put the polygon or polygon
  82950. // fragments in the appropriate lists. Coplanar polygons go into either
  82951. // `coplanarFront` or `coplanarBack` depending on their orientation with
  82952. // respect to this plane. Polygons in front or in back of this plane go into
  82953. // either `front` or `back`.
  82954. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  82955. var COPLANAR = 0;
  82956. var FRONT = 1;
  82957. var BACK = 2;
  82958. var SPANNING = 3;
  82959. // Classify each point as well as the entire polygon into one of the above
  82960. // four classes.
  82961. var polygonType = 0;
  82962. var types = [];
  82963. var i;
  82964. var t;
  82965. for (i = 0; i < polygon.vertices.length; i++) {
  82966. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  82967. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  82968. polygonType |= type;
  82969. types.push(type);
  82970. }
  82971. // Put the polygon in the correct list, splitting it when necessary.
  82972. switch (polygonType) {
  82973. case COPLANAR:
  82974. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  82975. break;
  82976. case FRONT:
  82977. front.push(polygon);
  82978. break;
  82979. case BACK:
  82980. back.push(polygon);
  82981. break;
  82982. case SPANNING:
  82983. var f = [], b = [];
  82984. for (i = 0; i < polygon.vertices.length; i++) {
  82985. var j = (i + 1) % polygon.vertices.length;
  82986. var ti = types[i], tj = types[j];
  82987. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  82988. if (ti !== BACK)
  82989. f.push(vi);
  82990. if (ti !== FRONT)
  82991. b.push(ti !== BACK ? vi.clone() : vi);
  82992. if ((ti | tj) === SPANNING) {
  82993. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  82994. var v = vi.interpolate(vj, t);
  82995. f.push(v);
  82996. b.push(v.clone());
  82997. }
  82998. }
  82999. var poly;
  83000. if (f.length >= 3) {
  83001. poly = new Polygon(f, polygon.shared);
  83002. if (poly.plane)
  83003. front.push(poly);
  83004. }
  83005. if (b.length >= 3) {
  83006. poly = new Polygon(b, polygon.shared);
  83007. if (poly.plane)
  83008. back.push(poly);
  83009. }
  83010. break;
  83011. }
  83012. };
  83013. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  83014. // point is on the plane.
  83015. Plane.EPSILON = 1e-5;
  83016. return Plane;
  83017. }());
  83018. // # class Polygon
  83019. // Represents a convex polygon. The vertices used to initialize a polygon must
  83020. // be coplanar and form a convex loop.
  83021. //
  83022. // Each convex polygon has a `shared` property, which is shared between all
  83023. // polygons that are clones of each other or were split from the same polygon.
  83024. // This can be used to define per-polygon properties (such as surface color).
  83025. var Polygon = /** @class */ (function () {
  83026. function Polygon(vertices, shared) {
  83027. this.vertices = vertices;
  83028. this.shared = shared;
  83029. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  83030. }
  83031. Polygon.prototype.clone = function () {
  83032. var vertices = this.vertices.map(function (v) { return v.clone(); });
  83033. return new Polygon(vertices, this.shared);
  83034. };
  83035. Polygon.prototype.flip = function () {
  83036. this.vertices.reverse().map(function (v) { v.flip(); });
  83037. this.plane.flip();
  83038. };
  83039. return Polygon;
  83040. }());
  83041. // # class Node
  83042. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  83043. // by picking a polygon to split along. That polygon (and all other coplanar
  83044. // polygons) are added directly to that node and the other polygons are added to
  83045. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  83046. // no distinction between internal and leaf nodes.
  83047. var Node = /** @class */ (function () {
  83048. function Node(polygons) {
  83049. this.plane = null;
  83050. this.front = null;
  83051. this.back = null;
  83052. this.polygons = new Array();
  83053. if (polygons) {
  83054. this.build(polygons);
  83055. }
  83056. }
  83057. Node.prototype.clone = function () {
  83058. var node = new Node();
  83059. node.plane = this.plane && this.plane.clone();
  83060. node.front = this.front && this.front.clone();
  83061. node.back = this.back && this.back.clone();
  83062. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  83063. return node;
  83064. };
  83065. // Convert solid space to empty space and empty space to solid space.
  83066. Node.prototype.invert = function () {
  83067. for (var i = 0; i < this.polygons.length; i++) {
  83068. this.polygons[i].flip();
  83069. }
  83070. if (this.plane) {
  83071. this.plane.flip();
  83072. }
  83073. if (this.front) {
  83074. this.front.invert();
  83075. }
  83076. if (this.back) {
  83077. this.back.invert();
  83078. }
  83079. var temp = this.front;
  83080. this.front = this.back;
  83081. this.back = temp;
  83082. };
  83083. // Recursively remove all polygons in `polygons` that are inside this BSP
  83084. // tree.
  83085. Node.prototype.clipPolygons = function (polygons) {
  83086. if (!this.plane)
  83087. return polygons.slice();
  83088. var front = new Array(), back = new Array();
  83089. for (var i = 0; i < polygons.length; i++) {
  83090. this.plane.splitPolygon(polygons[i], front, back, front, back);
  83091. }
  83092. if (this.front) {
  83093. front = this.front.clipPolygons(front);
  83094. }
  83095. if (this.back) {
  83096. back = this.back.clipPolygons(back);
  83097. }
  83098. else {
  83099. back = [];
  83100. }
  83101. return front.concat(back);
  83102. };
  83103. // Remove all polygons in this BSP tree that are inside the other BSP tree
  83104. // `bsp`.
  83105. Node.prototype.clipTo = function (bsp) {
  83106. this.polygons = bsp.clipPolygons(this.polygons);
  83107. if (this.front)
  83108. this.front.clipTo(bsp);
  83109. if (this.back)
  83110. this.back.clipTo(bsp);
  83111. };
  83112. // Return a list of all polygons in this BSP tree.
  83113. Node.prototype.allPolygons = function () {
  83114. var polygons = this.polygons.slice();
  83115. if (this.front)
  83116. polygons = polygons.concat(this.front.allPolygons());
  83117. if (this.back)
  83118. polygons = polygons.concat(this.back.allPolygons());
  83119. return polygons;
  83120. };
  83121. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  83122. // new polygons are filtered down to the bottom of the tree and become new
  83123. // nodes there. Each set of polygons is partitioned using the first polygon
  83124. // (no heuristic is used to pick a good split).
  83125. Node.prototype.build = function (polygons) {
  83126. if (!polygons.length)
  83127. return;
  83128. if (!this.plane)
  83129. this.plane = polygons[0].plane.clone();
  83130. var front = new Array(), back = new Array();
  83131. for (var i = 0; i < polygons.length; i++) {
  83132. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  83133. }
  83134. if (front.length) {
  83135. if (!this.front)
  83136. this.front = new Node();
  83137. this.front.build(front);
  83138. }
  83139. if (back.length) {
  83140. if (!this.back)
  83141. this.back = new Node();
  83142. this.back.build(back);
  83143. }
  83144. };
  83145. return Node;
  83146. }());
  83147. var CSG = /** @class */ (function () {
  83148. function CSG() {
  83149. this.polygons = new Array();
  83150. }
  83151. // Convert BABYLON.Mesh to BABYLON.CSG
  83152. CSG.FromMesh = function (mesh) {
  83153. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  83154. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  83155. if (mesh instanceof BABYLON.Mesh) {
  83156. mesh.computeWorldMatrix(true);
  83157. matrix = mesh.getWorldMatrix();
  83158. meshPosition = mesh.position.clone();
  83159. meshRotation = mesh.rotation.clone();
  83160. if (mesh.rotationQuaternion) {
  83161. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  83162. }
  83163. meshScaling = mesh.scaling.clone();
  83164. }
  83165. else {
  83166. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  83167. }
  83168. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83169. var subMeshes = mesh.subMeshes;
  83170. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  83171. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  83172. vertices = [];
  83173. for (var j = 0; j < 3; j++) {
  83174. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  83175. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  83176. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  83177. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  83178. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  83179. vertex = new Vertex(position, normal, uv);
  83180. vertices.push(vertex);
  83181. }
  83182. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  83183. // To handle the case of degenerated triangle
  83184. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  83185. if (polygon.plane)
  83186. polygons.push(polygon);
  83187. }
  83188. }
  83189. var csg = CSG.FromPolygons(polygons);
  83190. csg.matrix = matrix;
  83191. csg.position = meshPosition;
  83192. csg.rotation = meshRotation;
  83193. csg.scaling = meshScaling;
  83194. csg.rotationQuaternion = meshRotationQuaternion;
  83195. currentCSGMeshId++;
  83196. return csg;
  83197. };
  83198. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  83199. CSG.FromPolygons = function (polygons) {
  83200. var csg = new CSG();
  83201. csg.polygons = polygons;
  83202. return csg;
  83203. };
  83204. CSG.prototype.clone = function () {
  83205. var csg = new CSG();
  83206. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  83207. csg.copyTransformAttributes(this);
  83208. return csg;
  83209. };
  83210. CSG.prototype.union = function (csg) {
  83211. var a = new Node(this.clone().polygons);
  83212. var b = new Node(csg.clone().polygons);
  83213. a.clipTo(b);
  83214. b.clipTo(a);
  83215. b.invert();
  83216. b.clipTo(a);
  83217. b.invert();
  83218. a.build(b.allPolygons());
  83219. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83220. };
  83221. CSG.prototype.unionInPlace = function (csg) {
  83222. var a = new Node(this.polygons);
  83223. var b = new Node(csg.polygons);
  83224. a.clipTo(b);
  83225. b.clipTo(a);
  83226. b.invert();
  83227. b.clipTo(a);
  83228. b.invert();
  83229. a.build(b.allPolygons());
  83230. this.polygons = a.allPolygons();
  83231. };
  83232. CSG.prototype.subtract = function (csg) {
  83233. var a = new Node(this.clone().polygons);
  83234. var b = new Node(csg.clone().polygons);
  83235. a.invert();
  83236. a.clipTo(b);
  83237. b.clipTo(a);
  83238. b.invert();
  83239. b.clipTo(a);
  83240. b.invert();
  83241. a.build(b.allPolygons());
  83242. a.invert();
  83243. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83244. };
  83245. CSG.prototype.subtractInPlace = function (csg) {
  83246. var a = new Node(this.polygons);
  83247. var b = new Node(csg.polygons);
  83248. a.invert();
  83249. a.clipTo(b);
  83250. b.clipTo(a);
  83251. b.invert();
  83252. b.clipTo(a);
  83253. b.invert();
  83254. a.build(b.allPolygons());
  83255. a.invert();
  83256. this.polygons = a.allPolygons();
  83257. };
  83258. CSG.prototype.intersect = function (csg) {
  83259. var a = new Node(this.clone().polygons);
  83260. var b = new Node(csg.clone().polygons);
  83261. a.invert();
  83262. b.clipTo(a);
  83263. b.invert();
  83264. a.clipTo(b);
  83265. b.clipTo(a);
  83266. a.build(b.allPolygons());
  83267. a.invert();
  83268. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83269. };
  83270. CSG.prototype.intersectInPlace = function (csg) {
  83271. var a = new Node(this.polygons);
  83272. var b = new Node(csg.polygons);
  83273. a.invert();
  83274. b.clipTo(a);
  83275. b.invert();
  83276. a.clipTo(b);
  83277. b.clipTo(a);
  83278. a.build(b.allPolygons());
  83279. a.invert();
  83280. this.polygons = a.allPolygons();
  83281. };
  83282. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  83283. // not modified.
  83284. CSG.prototype.inverse = function () {
  83285. var csg = this.clone();
  83286. csg.inverseInPlace();
  83287. return csg;
  83288. };
  83289. CSG.prototype.inverseInPlace = function () {
  83290. this.polygons.map(function (p) { p.flip(); });
  83291. };
  83292. // This is used to keep meshes transformations so they can be restored
  83293. // when we build back a Babylon Mesh
  83294. // NB : All CSG operations are performed in world coordinates
  83295. CSG.prototype.copyTransformAttributes = function (csg) {
  83296. this.matrix = csg.matrix;
  83297. this.position = csg.position;
  83298. this.rotation = csg.rotation;
  83299. this.scaling = csg.scaling;
  83300. this.rotationQuaternion = csg.rotationQuaternion;
  83301. return this;
  83302. };
  83303. // Build Raw mesh from CSG
  83304. // Coordinates here are in world space
  83305. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  83306. var matrix = this.matrix.clone();
  83307. matrix.invert();
  83308. 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;
  83309. if (keepSubMeshes) {
  83310. // Sort Polygons, since subMeshes are indices range
  83311. polygons.sort(function (a, b) {
  83312. if (a.shared.meshId === b.shared.meshId) {
  83313. return a.shared.subMeshId - b.shared.subMeshId;
  83314. }
  83315. else {
  83316. return a.shared.meshId - b.shared.meshId;
  83317. }
  83318. });
  83319. }
  83320. for (var i = 0, il = polygons.length; i < il; i++) {
  83321. polygon = polygons[i];
  83322. // Building SubMeshes
  83323. if (!subMesh_dict[polygon.shared.meshId]) {
  83324. subMesh_dict[polygon.shared.meshId] = {};
  83325. }
  83326. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  83327. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  83328. indexStart: +Infinity,
  83329. indexEnd: -Infinity,
  83330. materialIndex: polygon.shared.materialIndex
  83331. };
  83332. }
  83333. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  83334. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  83335. polygonIndices[0] = 0;
  83336. polygonIndices[1] = j - 1;
  83337. polygonIndices[2] = j;
  83338. for (var k = 0; k < 3; k++) {
  83339. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  83340. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  83341. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  83342. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  83343. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  83344. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  83345. // Check if 2 points can be merged
  83346. if (!(typeof vertex_idx !== 'undefined' &&
  83347. normals[vertex_idx * 3] === localNormal.x &&
  83348. normals[vertex_idx * 3 + 1] === localNormal.y &&
  83349. normals[vertex_idx * 3 + 2] === localNormal.z &&
  83350. uvs[vertex_idx * 2] === uv.x &&
  83351. uvs[vertex_idx * 2 + 1] === uv.y)) {
  83352. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  83353. uvs.push(uv.x, uv.y);
  83354. normals.push(normal.x, normal.y, normal.z);
  83355. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  83356. }
  83357. indices.push(vertex_idx);
  83358. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  83359. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  83360. currentIndex++;
  83361. }
  83362. }
  83363. }
  83364. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  83365. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  83366. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  83367. mesh.setIndices(indices, null);
  83368. if (keepSubMeshes) {
  83369. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  83370. var materialIndexOffset = 0, materialMaxIndex;
  83371. mesh.subMeshes = new Array();
  83372. for (var m in subMesh_dict) {
  83373. materialMaxIndex = -1;
  83374. for (var sm in subMesh_dict[m]) {
  83375. subMesh_obj = subMesh_dict[m][sm];
  83376. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  83377. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  83378. }
  83379. materialIndexOffset += ++materialMaxIndex;
  83380. }
  83381. }
  83382. return mesh;
  83383. };
  83384. // Build Mesh from CSG taking material and transforms into account
  83385. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  83386. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  83387. mesh.material = material;
  83388. mesh.position.copyFrom(this.position);
  83389. mesh.rotation.copyFrom(this.rotation);
  83390. if (this.rotationQuaternion) {
  83391. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  83392. }
  83393. mesh.scaling.copyFrom(this.scaling);
  83394. mesh.computeWorldMatrix(true);
  83395. return mesh;
  83396. };
  83397. return CSG;
  83398. }());
  83399. BABYLON.CSG = CSG;
  83400. })(BABYLON || (BABYLON = {}));
  83401. //# sourceMappingURL=babylon.csg.js.map
  83402. var BABYLON;
  83403. (function (BABYLON) {
  83404. var LensFlare = /** @class */ (function () {
  83405. function LensFlare(size, position, color, imgUrl, system) {
  83406. this.size = size;
  83407. this.position = position;
  83408. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  83409. this.color = color || new BABYLON.Color3(1, 1, 1);
  83410. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  83411. this._system = system;
  83412. system.lensFlares.push(this);
  83413. }
  83414. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  83415. return new LensFlare(size, position, color, imgUrl, system);
  83416. };
  83417. LensFlare.prototype.dispose = function () {
  83418. if (this.texture) {
  83419. this.texture.dispose();
  83420. }
  83421. // Remove from scene
  83422. var index = this._system.lensFlares.indexOf(this);
  83423. this._system.lensFlares.splice(index, 1);
  83424. };
  83425. ;
  83426. return LensFlare;
  83427. }());
  83428. BABYLON.LensFlare = LensFlare;
  83429. })(BABYLON || (BABYLON = {}));
  83430. //# sourceMappingURL=babylon.lensFlare.js.map
  83431. var BABYLON;
  83432. (function (BABYLON) {
  83433. var LensFlareSystem = /** @class */ (function () {
  83434. function LensFlareSystem(name, emitter, scene) {
  83435. this.name = name;
  83436. this.lensFlares = new Array();
  83437. this.borderLimit = 300;
  83438. this.viewportBorder = 0;
  83439. this.layerMask = 0x0FFFFFFF;
  83440. this._vertexBuffers = {};
  83441. this._isEnabled = true;
  83442. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83443. this._emitter = emitter;
  83444. this.id = name;
  83445. scene.lensFlareSystems.push(this);
  83446. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  83447. var engine = scene.getEngine();
  83448. // VBO
  83449. var vertices = [];
  83450. vertices.push(1, 1);
  83451. vertices.push(-1, 1);
  83452. vertices.push(-1, -1);
  83453. vertices.push(1, -1);
  83454. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  83455. // Indices
  83456. var indices = [];
  83457. indices.push(0);
  83458. indices.push(1);
  83459. indices.push(2);
  83460. indices.push(0);
  83461. indices.push(2);
  83462. indices.push(3);
  83463. this._indexBuffer = engine.createIndexBuffer(indices);
  83464. // Effects
  83465. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  83466. }
  83467. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  83468. get: function () {
  83469. return this._isEnabled;
  83470. },
  83471. set: function (value) {
  83472. this._isEnabled = value;
  83473. },
  83474. enumerable: true,
  83475. configurable: true
  83476. });
  83477. LensFlareSystem.prototype.getScene = function () {
  83478. return this._scene;
  83479. };
  83480. LensFlareSystem.prototype.getEmitter = function () {
  83481. return this._emitter;
  83482. };
  83483. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  83484. this._emitter = newEmitter;
  83485. };
  83486. LensFlareSystem.prototype.getEmitterPosition = function () {
  83487. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  83488. };
  83489. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  83490. var position = this.getEmitterPosition();
  83491. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  83492. this._positionX = position.x;
  83493. this._positionY = position.y;
  83494. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  83495. if (this.viewportBorder > 0) {
  83496. globalViewport.x -= this.viewportBorder;
  83497. globalViewport.y -= this.viewportBorder;
  83498. globalViewport.width += this.viewportBorder * 2;
  83499. globalViewport.height += this.viewportBorder * 2;
  83500. position.x += this.viewportBorder;
  83501. position.y += this.viewportBorder;
  83502. this._positionX += this.viewportBorder;
  83503. this._positionY += this.viewportBorder;
  83504. }
  83505. if (position.z > 0) {
  83506. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  83507. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  83508. return true;
  83509. }
  83510. return true;
  83511. }
  83512. return false;
  83513. };
  83514. LensFlareSystem.prototype._isVisible = function () {
  83515. if (!this._isEnabled || !this._scene.activeCamera) {
  83516. return false;
  83517. }
  83518. var emitterPosition = this.getEmitterPosition();
  83519. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  83520. var distance = direction.length();
  83521. direction.normalize();
  83522. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  83523. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  83524. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  83525. };
  83526. LensFlareSystem.prototype.render = function () {
  83527. if (!this._effect.isReady() || !this._scene.activeCamera)
  83528. return false;
  83529. var engine = this._scene.getEngine();
  83530. var viewport = this._scene.activeCamera.viewport;
  83531. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  83532. // Position
  83533. if (!this.computeEffectivePosition(globalViewport)) {
  83534. return false;
  83535. }
  83536. // Visibility
  83537. if (!this._isVisible()) {
  83538. return false;
  83539. }
  83540. // Intensity
  83541. var awayX;
  83542. var awayY;
  83543. if (this._positionX < this.borderLimit + globalViewport.x) {
  83544. awayX = this.borderLimit + globalViewport.x - this._positionX;
  83545. }
  83546. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  83547. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  83548. }
  83549. else {
  83550. awayX = 0;
  83551. }
  83552. if (this._positionY < this.borderLimit + globalViewport.y) {
  83553. awayY = this.borderLimit + globalViewport.y - this._positionY;
  83554. }
  83555. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  83556. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  83557. }
  83558. else {
  83559. awayY = 0;
  83560. }
  83561. var away = (awayX > awayY) ? awayX : awayY;
  83562. away -= this.viewportBorder;
  83563. if (away > this.borderLimit) {
  83564. away = this.borderLimit;
  83565. }
  83566. var intensity = 1.0 - (away / this.borderLimit);
  83567. if (intensity < 0) {
  83568. return false;
  83569. }
  83570. if (intensity > 1.0) {
  83571. intensity = 1.0;
  83572. }
  83573. if (this.viewportBorder > 0) {
  83574. globalViewport.x += this.viewportBorder;
  83575. globalViewport.y += this.viewportBorder;
  83576. globalViewport.width -= this.viewportBorder * 2;
  83577. globalViewport.height -= this.viewportBorder * 2;
  83578. this._positionX -= this.viewportBorder;
  83579. this._positionY -= this.viewportBorder;
  83580. }
  83581. // Position
  83582. var centerX = globalViewport.x + globalViewport.width / 2;
  83583. var centerY = globalViewport.y + globalViewport.height / 2;
  83584. var distX = centerX - this._positionX;
  83585. var distY = centerY - this._positionY;
  83586. // Effects
  83587. engine.enableEffect(this._effect);
  83588. engine.setState(false);
  83589. engine.setDepthBuffer(false);
  83590. // VBOs
  83591. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  83592. // Flares
  83593. for (var index = 0; index < this.lensFlares.length; index++) {
  83594. var flare = this.lensFlares[index];
  83595. engine.setAlphaMode(flare.alphaMode);
  83596. var x = centerX - (distX * flare.position);
  83597. var y = centerY - (distY * flare.position);
  83598. var cw = flare.size;
  83599. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  83600. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  83601. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  83602. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  83603. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  83604. // Texture
  83605. this._effect.setTexture("textureSampler", flare.texture);
  83606. // Color
  83607. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  83608. // Draw order
  83609. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83610. }
  83611. engine.setDepthBuffer(true);
  83612. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  83613. return true;
  83614. };
  83615. LensFlareSystem.prototype.dispose = function () {
  83616. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83617. if (vertexBuffer) {
  83618. vertexBuffer.dispose();
  83619. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  83620. }
  83621. if (this._indexBuffer) {
  83622. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  83623. this._indexBuffer = null;
  83624. }
  83625. while (this.lensFlares.length) {
  83626. this.lensFlares[0].dispose();
  83627. }
  83628. // Remove from scene
  83629. var index = this._scene.lensFlareSystems.indexOf(this);
  83630. this._scene.lensFlareSystems.splice(index, 1);
  83631. };
  83632. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  83633. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  83634. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  83635. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  83636. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  83637. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  83638. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  83639. var parsedFlare = parsedLensFlareSystem.flares[index];
  83640. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  83641. }
  83642. return lensFlareSystem;
  83643. };
  83644. LensFlareSystem.prototype.serialize = function () {
  83645. var serializationObject = {};
  83646. serializationObject.id = this.id;
  83647. serializationObject.name = this.name;
  83648. serializationObject.emitterId = this.getEmitter().id;
  83649. serializationObject.borderLimit = this.borderLimit;
  83650. serializationObject.flares = [];
  83651. for (var index = 0; index < this.lensFlares.length; index++) {
  83652. var flare = this.lensFlares[index];
  83653. serializationObject.flares.push({
  83654. size: flare.size,
  83655. position: flare.position,
  83656. color: flare.color.asArray(),
  83657. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  83658. });
  83659. }
  83660. return serializationObject;
  83661. };
  83662. return LensFlareSystem;
  83663. }());
  83664. BABYLON.LensFlareSystem = LensFlareSystem;
  83665. })(BABYLON || (BABYLON = {}));
  83666. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  83667. var BABYLON;
  83668. (function (BABYLON) {
  83669. /**
  83670. * This is a holder class for the physics joint created by the physics plugin.
  83671. * It holds a set of functions to control the underlying joint.
  83672. */
  83673. var PhysicsJoint = /** @class */ (function () {
  83674. function PhysicsJoint(type, jointData) {
  83675. this.type = type;
  83676. this.jointData = jointData;
  83677. jointData.nativeParams = jointData.nativeParams || {};
  83678. }
  83679. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  83680. get: function () {
  83681. return this._physicsJoint;
  83682. },
  83683. set: function (newJoint) {
  83684. if (this._physicsJoint) {
  83685. //remove from the wolrd
  83686. }
  83687. this._physicsJoint = newJoint;
  83688. },
  83689. enumerable: true,
  83690. configurable: true
  83691. });
  83692. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  83693. set: function (physicsPlugin) {
  83694. this._physicsPlugin = physicsPlugin;
  83695. },
  83696. enumerable: true,
  83697. configurable: true
  83698. });
  83699. /**
  83700. * Execute a function that is physics-plugin specific.
  83701. * @param {Function} func the function that will be executed.
  83702. * It accepts two parameters: the physics world and the physics joint.
  83703. */
  83704. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  83705. func(this._physicsPlugin.world, this._physicsJoint);
  83706. };
  83707. //TODO check if the native joints are the same
  83708. //Joint Types
  83709. PhysicsJoint.DistanceJoint = 0;
  83710. PhysicsJoint.HingeJoint = 1;
  83711. PhysicsJoint.BallAndSocketJoint = 2;
  83712. PhysicsJoint.WheelJoint = 3;
  83713. PhysicsJoint.SliderJoint = 4;
  83714. //OIMO
  83715. PhysicsJoint.PrismaticJoint = 5;
  83716. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  83717. PhysicsJoint.UniversalJoint = 6;
  83718. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  83719. //Cannon
  83720. //Similar to a Ball-Joint. Different in params
  83721. PhysicsJoint.PointToPointJoint = 8;
  83722. //Cannon only at the moment
  83723. PhysicsJoint.SpringJoint = 9;
  83724. PhysicsJoint.LockJoint = 10;
  83725. return PhysicsJoint;
  83726. }());
  83727. BABYLON.PhysicsJoint = PhysicsJoint;
  83728. /**
  83729. * A class representing a physics distance joint.
  83730. */
  83731. var DistanceJoint = /** @class */ (function (_super) {
  83732. __extends(DistanceJoint, _super);
  83733. function DistanceJoint(jointData) {
  83734. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  83735. }
  83736. /**
  83737. * Update the predefined distance.
  83738. */
  83739. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  83740. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  83741. };
  83742. return DistanceJoint;
  83743. }(PhysicsJoint));
  83744. BABYLON.DistanceJoint = DistanceJoint;
  83745. var MotorEnabledJoint = /** @class */ (function (_super) {
  83746. __extends(MotorEnabledJoint, _super);
  83747. function MotorEnabledJoint(type, jointData) {
  83748. return _super.call(this, type, jointData) || this;
  83749. }
  83750. /**
  83751. * Set the motor values.
  83752. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83753. * @param {number} force the force to apply
  83754. * @param {number} maxForce max force for this motor.
  83755. */
  83756. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  83757. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83758. };
  83759. /**
  83760. * Set the motor's limits.
  83761. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83762. */
  83763. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83764. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83765. };
  83766. return MotorEnabledJoint;
  83767. }(PhysicsJoint));
  83768. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  83769. /**
  83770. * This class represents a single hinge physics joint
  83771. */
  83772. var HingeJoint = /** @class */ (function (_super) {
  83773. __extends(HingeJoint, _super);
  83774. function HingeJoint(jointData) {
  83775. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  83776. }
  83777. /**
  83778. * Set the motor values.
  83779. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83780. * @param {number} force the force to apply
  83781. * @param {number} maxForce max force for this motor.
  83782. */
  83783. HingeJoint.prototype.setMotor = function (force, maxForce) {
  83784. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83785. };
  83786. /**
  83787. * Set the motor's limits.
  83788. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83789. */
  83790. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83791. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83792. };
  83793. return HingeJoint;
  83794. }(MotorEnabledJoint));
  83795. BABYLON.HingeJoint = HingeJoint;
  83796. /**
  83797. * This class represents a dual hinge physics joint (same as wheel joint)
  83798. */
  83799. var Hinge2Joint = /** @class */ (function (_super) {
  83800. __extends(Hinge2Joint, _super);
  83801. function Hinge2Joint(jointData) {
  83802. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  83803. }
  83804. /**
  83805. * Set the motor values.
  83806. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83807. * @param {number} force the force to apply
  83808. * @param {number} maxForce max force for this motor.
  83809. * @param {motorIndex} the motor's index, 0 or 1.
  83810. */
  83811. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  83812. if (motorIndex === void 0) { motorIndex = 0; }
  83813. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  83814. };
  83815. /**
  83816. * Set the motor limits.
  83817. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83818. * @param {number} upperLimit the upper limit
  83819. * @param {number} lowerLimit lower limit
  83820. * @param {motorIndex} the motor's index, 0 or 1.
  83821. */
  83822. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  83823. if (motorIndex === void 0) { motorIndex = 0; }
  83824. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  83825. };
  83826. return Hinge2Joint;
  83827. }(MotorEnabledJoint));
  83828. BABYLON.Hinge2Joint = Hinge2Joint;
  83829. })(BABYLON || (BABYLON = {}));
  83830. //# sourceMappingURL=babylon.physicsJoint.js.map
  83831. var BABYLON;
  83832. (function (BABYLON) {
  83833. var PhysicsImpostor = /** @class */ (function () {
  83834. function PhysicsImpostor(object, type, _options, _scene) {
  83835. if (_options === void 0) { _options = { mass: 0 }; }
  83836. var _this = this;
  83837. this.object = object;
  83838. this.type = type;
  83839. this._options = _options;
  83840. this._scene = _scene;
  83841. this._bodyUpdateRequired = false;
  83842. this._onBeforePhysicsStepCallbacks = new Array();
  83843. this._onAfterPhysicsStepCallbacks = new Array();
  83844. this._onPhysicsCollideCallbacks = [];
  83845. this._deltaPosition = BABYLON.Vector3.Zero();
  83846. this._isDisposed = false;
  83847. //temp variables for parent rotation calculations
  83848. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  83849. this._tmpQuat = new BABYLON.Quaternion();
  83850. this._tmpQuat2 = new BABYLON.Quaternion();
  83851. /**
  83852. * this function is executed by the physics engine.
  83853. */
  83854. this.beforeStep = function () {
  83855. if (!_this._physicsEngine) {
  83856. return;
  83857. }
  83858. _this.object.translate(_this._deltaPosition, -1);
  83859. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  83860. _this.object.computeWorldMatrix(false);
  83861. if (_this.object.parent && _this.object.rotationQuaternion) {
  83862. _this.getParentsRotation();
  83863. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  83864. }
  83865. else {
  83866. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  83867. }
  83868. if (!_this._options.disableBidirectionalTransformation) {
  83869. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  83870. }
  83871. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  83872. func(_this);
  83873. });
  83874. };
  83875. /**
  83876. * this function is executed by the physics engine.
  83877. */
  83878. this.afterStep = function () {
  83879. if (!_this._physicsEngine) {
  83880. return;
  83881. }
  83882. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  83883. func(_this);
  83884. });
  83885. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  83886. // object has now its world rotation. needs to be converted to local.
  83887. if (_this.object.parent && _this.object.rotationQuaternion) {
  83888. _this.getParentsRotation();
  83889. _this._tmpQuat.conjugateInPlace();
  83890. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  83891. }
  83892. // take the position set and make it the absolute position of this object.
  83893. _this.object.setAbsolutePosition(_this.object.position);
  83894. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  83895. _this.object.translate(_this._deltaPosition, 1);
  83896. };
  83897. /**
  83898. * Legacy collision detection event support
  83899. */
  83900. this.onCollideEvent = null;
  83901. //event and body object due to cannon's event-based architecture.
  83902. this.onCollide = function (e) {
  83903. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  83904. return;
  83905. }
  83906. if (!_this._physicsEngine) {
  83907. return;
  83908. }
  83909. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  83910. if (otherImpostor) {
  83911. // Legacy collision detection event support
  83912. if (_this.onCollideEvent) {
  83913. _this.onCollideEvent(_this, otherImpostor);
  83914. }
  83915. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  83916. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  83917. }).forEach(function (obj) {
  83918. obj.callback(_this, otherImpostor);
  83919. });
  83920. }
  83921. };
  83922. //sanity check!
  83923. if (!this.object) {
  83924. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  83925. return;
  83926. }
  83927. //legacy support for old syntax.
  83928. if (!this._scene && object.getScene) {
  83929. this._scene = object.getScene();
  83930. }
  83931. if (!this._scene) {
  83932. return;
  83933. }
  83934. this._physicsEngine = this._scene.getPhysicsEngine();
  83935. if (!this._physicsEngine) {
  83936. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  83937. }
  83938. else {
  83939. //set the object's quaternion, if not set
  83940. if (!this.object.rotationQuaternion) {
  83941. if (this.object.rotation) {
  83942. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  83943. }
  83944. else {
  83945. this.object.rotationQuaternion = new BABYLON.Quaternion();
  83946. }
  83947. }
  83948. //default options params
  83949. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  83950. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  83951. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  83952. this._joints = [];
  83953. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  83954. if (!this.object.parent || this._options.ignoreParent) {
  83955. this._init();
  83956. }
  83957. else if (this.object.parent.physicsImpostor) {
  83958. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  83959. }
  83960. }
  83961. }
  83962. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  83963. get: function () {
  83964. return this._isDisposed;
  83965. },
  83966. enumerable: true,
  83967. configurable: true
  83968. });
  83969. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  83970. get: function () {
  83971. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  83972. },
  83973. set: function (value) {
  83974. this.setMass(value);
  83975. },
  83976. enumerable: true,
  83977. configurable: true
  83978. });
  83979. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  83980. get: function () {
  83981. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  83982. },
  83983. set: function (value) {
  83984. if (!this._physicsEngine) {
  83985. return;
  83986. }
  83987. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  83988. },
  83989. enumerable: true,
  83990. configurable: true
  83991. });
  83992. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  83993. get: function () {
  83994. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  83995. },
  83996. set: function (value) {
  83997. if (!this._physicsEngine) {
  83998. return;
  83999. }
  84000. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  84001. },
  84002. enumerable: true,
  84003. configurable: true
  84004. });
  84005. /**
  84006. * This function will completly initialize this impostor.
  84007. * It will create a new body - but only if this mesh has no parent.
  84008. * If it has, this impostor will not be used other than to define the impostor
  84009. * of the child mesh.
  84010. */
  84011. PhysicsImpostor.prototype._init = function () {
  84012. if (!this._physicsEngine) {
  84013. return;
  84014. }
  84015. this._physicsEngine.removeImpostor(this);
  84016. this.physicsBody = null;
  84017. this._parent = this._parent || this._getPhysicsParent();
  84018. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  84019. this._physicsEngine.addImpostor(this);
  84020. }
  84021. };
  84022. PhysicsImpostor.prototype._getPhysicsParent = function () {
  84023. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  84024. var parentMesh = this.object.parent;
  84025. return parentMesh.physicsImpostor;
  84026. }
  84027. return null;
  84028. };
  84029. /**
  84030. * Should a new body be generated.
  84031. */
  84032. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  84033. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  84034. };
  84035. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  84036. this.forceUpdate();
  84037. };
  84038. /**
  84039. * Force a regeneration of this or the parent's impostor's body.
  84040. * Use under cautious - This will remove all joints already implemented.
  84041. */
  84042. PhysicsImpostor.prototype.forceUpdate = function () {
  84043. this._init();
  84044. if (this.parent && !this._options.ignoreParent) {
  84045. this.parent.forceUpdate();
  84046. }
  84047. };
  84048. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  84049. /*public get mesh(): AbstractMesh {
  84050. return this._mesh;
  84051. }*/
  84052. /**
  84053. * Gets the body that holds this impostor. Either its own, or its parent.
  84054. */
  84055. get: function () {
  84056. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  84057. },
  84058. /**
  84059. * Set the physics body. Used mainly by the physics engine/plugin
  84060. */
  84061. set: function (physicsBody) {
  84062. if (this._physicsBody && this._physicsEngine) {
  84063. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  84064. }
  84065. this._physicsBody = physicsBody;
  84066. this.resetUpdateFlags();
  84067. },
  84068. enumerable: true,
  84069. configurable: true
  84070. });
  84071. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  84072. get: function () {
  84073. return !this._options.ignoreParent && this._parent ? this._parent : null;
  84074. },
  84075. set: function (value) {
  84076. this._parent = value;
  84077. },
  84078. enumerable: true,
  84079. configurable: true
  84080. });
  84081. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  84082. this._bodyUpdateRequired = false;
  84083. };
  84084. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  84085. if (this.object.getBoundingInfo) {
  84086. var q = this.object.rotationQuaternion;
  84087. //reset rotation
  84088. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  84089. //calculate the world matrix with no rotation
  84090. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84091. var boundingInfo = this.object.getBoundingInfo();
  84092. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  84093. //bring back the rotation
  84094. this.object.rotationQuaternion = q;
  84095. //calculate the world matrix with the new rotation
  84096. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84097. return size;
  84098. }
  84099. else {
  84100. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  84101. }
  84102. };
  84103. PhysicsImpostor.prototype.getObjectCenter = function () {
  84104. if (this.object.getBoundingInfo) {
  84105. var boundingInfo = this.object.getBoundingInfo();
  84106. return boundingInfo.boundingBox.centerWorld;
  84107. }
  84108. else {
  84109. return this.object.position;
  84110. }
  84111. };
  84112. /**
  84113. * Get a specific parametes from the options parameter.
  84114. */
  84115. PhysicsImpostor.prototype.getParam = function (paramName) {
  84116. return this._options[paramName];
  84117. };
  84118. /**
  84119. * Sets a specific parameter in the options given to the physics plugin
  84120. */
  84121. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  84122. this._options[paramName] = value;
  84123. this._bodyUpdateRequired = true;
  84124. };
  84125. /**
  84126. * Specifically change the body's mass option. Won't recreate the physics body object
  84127. */
  84128. PhysicsImpostor.prototype.setMass = function (mass) {
  84129. if (this.getParam("mass") !== mass) {
  84130. this.setParam("mass", mass);
  84131. }
  84132. if (this._physicsEngine) {
  84133. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  84134. }
  84135. };
  84136. PhysicsImpostor.prototype.getLinearVelocity = function () {
  84137. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  84138. };
  84139. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  84140. if (this._physicsEngine) {
  84141. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  84142. }
  84143. };
  84144. PhysicsImpostor.prototype.getAngularVelocity = function () {
  84145. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  84146. };
  84147. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  84148. if (this._physicsEngine) {
  84149. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  84150. }
  84151. };
  84152. /**
  84153. * Execute a function with the physics plugin native code.
  84154. * Provide a function the will have two variables - the world object and the physics body object.
  84155. */
  84156. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  84157. if (this._physicsEngine) {
  84158. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  84159. }
  84160. };
  84161. /**
  84162. * Register a function that will be executed before the physics world is stepping forward.
  84163. */
  84164. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  84165. this._onBeforePhysicsStepCallbacks.push(func);
  84166. };
  84167. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  84168. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  84169. if (index > -1) {
  84170. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  84171. }
  84172. else {
  84173. BABYLON.Tools.Warn("Function to remove was not found");
  84174. }
  84175. };
  84176. /**
  84177. * Register a function that will be executed after the physics step
  84178. */
  84179. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  84180. this._onAfterPhysicsStepCallbacks.push(func);
  84181. };
  84182. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  84183. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  84184. if (index > -1) {
  84185. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  84186. }
  84187. else {
  84188. BABYLON.Tools.Warn("Function to remove was not found");
  84189. }
  84190. };
  84191. /**
  84192. * register a function that will be executed when this impostor collides against a different body.
  84193. */
  84194. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  84195. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84196. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  84197. };
  84198. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  84199. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84200. var index = -1;
  84201. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  84202. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  84203. // chcek the arrays match
  84204. var sameList = cbDef.otherImpostors.every(function (impostor) {
  84205. return collidedAgainstList.indexOf(impostor) > -1;
  84206. });
  84207. if (sameList) {
  84208. index = idx;
  84209. }
  84210. return sameList;
  84211. }
  84212. return false;
  84213. });
  84214. if (found) {
  84215. this._onPhysicsCollideCallbacks.splice(index, 1);
  84216. }
  84217. else {
  84218. BABYLON.Tools.Warn("Function to remove was not found");
  84219. }
  84220. };
  84221. PhysicsImpostor.prototype.getParentsRotation = function () {
  84222. var parent = this.object.parent;
  84223. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  84224. while (parent) {
  84225. if (parent.rotationQuaternion) {
  84226. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  84227. }
  84228. else {
  84229. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  84230. }
  84231. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  84232. parent = parent.parent;
  84233. }
  84234. return this._tmpQuat;
  84235. };
  84236. /**
  84237. * Apply a force
  84238. */
  84239. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  84240. if (this._physicsEngine) {
  84241. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  84242. }
  84243. return this;
  84244. };
  84245. /**
  84246. * Apply an impulse
  84247. */
  84248. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  84249. if (this._physicsEngine) {
  84250. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  84251. }
  84252. return this;
  84253. };
  84254. /**
  84255. * A help function to create a joint.
  84256. */
  84257. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  84258. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  84259. this.addJoint(otherImpostor, joint);
  84260. return this;
  84261. };
  84262. /**
  84263. * Add a joint to this impostor with a different impostor.
  84264. */
  84265. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  84266. this._joints.push({
  84267. otherImpostor: otherImpostor,
  84268. joint: joint
  84269. });
  84270. if (this._physicsEngine) {
  84271. this._physicsEngine.addJoint(this, otherImpostor, joint);
  84272. }
  84273. return this;
  84274. };
  84275. /**
  84276. * Will keep this body still, in a sleep mode.
  84277. */
  84278. PhysicsImpostor.prototype.sleep = function () {
  84279. if (this._physicsEngine) {
  84280. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  84281. }
  84282. return this;
  84283. };
  84284. /**
  84285. * Wake the body up.
  84286. */
  84287. PhysicsImpostor.prototype.wakeUp = function () {
  84288. if (this._physicsEngine) {
  84289. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  84290. }
  84291. return this;
  84292. };
  84293. PhysicsImpostor.prototype.clone = function (newObject) {
  84294. if (!newObject)
  84295. return null;
  84296. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  84297. };
  84298. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  84299. var _this = this;
  84300. //no dispose if no physics engine is available.
  84301. if (!this._physicsEngine) {
  84302. return;
  84303. }
  84304. this._joints.forEach(function (j) {
  84305. if (_this._physicsEngine) {
  84306. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  84307. }
  84308. });
  84309. //dispose the physics body
  84310. this._physicsEngine.removeImpostor(this);
  84311. if (this.parent) {
  84312. this.parent.forceUpdate();
  84313. }
  84314. else {
  84315. /*this._object.getChildMeshes().forEach(function(mesh) {
  84316. if (mesh.physicsImpostor) {
  84317. if (disposeChildren) {
  84318. mesh.physicsImpostor.dispose();
  84319. mesh.physicsImpostor = null;
  84320. }
  84321. }
  84322. })*/
  84323. }
  84324. this._isDisposed = true;
  84325. };
  84326. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  84327. this._deltaPosition.copyFrom(position);
  84328. };
  84329. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  84330. if (!this._deltaRotation) {
  84331. this._deltaRotation = new BABYLON.Quaternion();
  84332. }
  84333. this._deltaRotation.copyFrom(rotation);
  84334. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  84335. };
  84336. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  84337. if (this._physicsEngine) {
  84338. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  84339. }
  84340. return this;
  84341. };
  84342. PhysicsImpostor.prototype.getRadius = function () {
  84343. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  84344. };
  84345. /**
  84346. * Sync a bone with this impostor
  84347. * @param bone The bone to sync to the impostor.
  84348. * @param boneMesh The mesh that the bone is influencing.
  84349. * @param jointPivot The pivot of the joint / bone in local space.
  84350. * @param distToJoint Optional distance from the impostor to the joint.
  84351. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  84352. */
  84353. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  84354. var tempVec = PhysicsImpostor._tmpVecs[0];
  84355. var mesh = this.object;
  84356. if (mesh.rotationQuaternion) {
  84357. if (adjustRotation) {
  84358. var tempQuat = PhysicsImpostor._tmpQuat;
  84359. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  84360. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  84361. }
  84362. else {
  84363. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  84364. }
  84365. }
  84366. tempVec.x = 0;
  84367. tempVec.y = 0;
  84368. tempVec.z = 0;
  84369. if (jointPivot) {
  84370. tempVec.x = jointPivot.x;
  84371. tempVec.y = jointPivot.y;
  84372. tempVec.z = jointPivot.z;
  84373. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  84374. if (distToJoint === undefined || distToJoint === null) {
  84375. distToJoint = jointPivot.length();
  84376. }
  84377. tempVec.x *= distToJoint;
  84378. tempVec.y *= distToJoint;
  84379. tempVec.z *= distToJoint;
  84380. }
  84381. if (bone.getParent()) {
  84382. tempVec.addInPlace(mesh.getAbsolutePosition());
  84383. bone.setAbsolutePosition(tempVec, boneMesh);
  84384. }
  84385. else {
  84386. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  84387. boneMesh.position.x -= tempVec.x;
  84388. boneMesh.position.y -= tempVec.y;
  84389. boneMesh.position.z -= tempVec.z;
  84390. }
  84391. };
  84392. /**
  84393. * Sync impostor to a bone
  84394. * @param bone The bone that the impostor will be synced to.
  84395. * @param boneMesh The mesh that the bone is influencing.
  84396. * @param jointPivot The pivot of the joint / bone in local space.
  84397. * @param distToJoint Optional distance from the impostor to the joint.
  84398. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  84399. * @param boneAxis Optional vector3 axis the bone is aligned with
  84400. */
  84401. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  84402. var mesh = this.object;
  84403. if (mesh.rotationQuaternion) {
  84404. if (adjustRotation) {
  84405. var tempQuat = PhysicsImpostor._tmpQuat;
  84406. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  84407. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  84408. }
  84409. else {
  84410. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  84411. }
  84412. }
  84413. var pos = PhysicsImpostor._tmpVecs[0];
  84414. var boneDir = PhysicsImpostor._tmpVecs[1];
  84415. if (!boneAxis) {
  84416. boneAxis = PhysicsImpostor._tmpVecs[2];
  84417. boneAxis.x = 0;
  84418. boneAxis.y = 1;
  84419. boneAxis.z = 0;
  84420. }
  84421. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  84422. bone.getAbsolutePositionToRef(boneMesh, pos);
  84423. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  84424. distToJoint = jointPivot.length();
  84425. }
  84426. if (distToJoint !== undefined && distToJoint !== null) {
  84427. pos.x += boneDir.x * distToJoint;
  84428. pos.y += boneDir.y * distToJoint;
  84429. pos.z += boneDir.z * distToJoint;
  84430. }
  84431. mesh.setAbsolutePosition(pos);
  84432. };
  84433. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  84434. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  84435. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84436. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  84437. //Impostor types
  84438. PhysicsImpostor.NoImpostor = 0;
  84439. PhysicsImpostor.SphereImpostor = 1;
  84440. PhysicsImpostor.BoxImpostor = 2;
  84441. PhysicsImpostor.PlaneImpostor = 3;
  84442. PhysicsImpostor.MeshImpostor = 4;
  84443. PhysicsImpostor.CylinderImpostor = 7;
  84444. PhysicsImpostor.ParticleImpostor = 8;
  84445. PhysicsImpostor.HeightmapImpostor = 9;
  84446. return PhysicsImpostor;
  84447. }());
  84448. BABYLON.PhysicsImpostor = PhysicsImpostor;
  84449. })(BABYLON || (BABYLON = {}));
  84450. //# sourceMappingURL=babylon.physicsImpostor.js.map
  84451. var BABYLON;
  84452. (function (BABYLON) {
  84453. var PhysicsEngine = /** @class */ (function () {
  84454. function PhysicsEngine(gravity, _physicsPlugin) {
  84455. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  84456. this._physicsPlugin = _physicsPlugin;
  84457. //new methods and parameters
  84458. this._impostors = [];
  84459. this._joints = [];
  84460. if (!this._physicsPlugin.isSupported()) {
  84461. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  84462. + "Please make sure it is included.");
  84463. }
  84464. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  84465. this.setGravity(gravity);
  84466. this.setTimeStep();
  84467. }
  84468. PhysicsEngine.prototype.setGravity = function (gravity) {
  84469. this.gravity = gravity;
  84470. this._physicsPlugin.setGravity(this.gravity);
  84471. };
  84472. /**
  84473. * Set the time step of the physics engine.
  84474. * default is 1/60.
  84475. * To slow it down, enter 1/600 for example.
  84476. * To speed it up, 1/30
  84477. * @param {number} newTimeStep the new timestep to apply to this world.
  84478. */
  84479. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  84480. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  84481. this._physicsPlugin.setTimeStep(newTimeStep);
  84482. };
  84483. /**
  84484. * Get the time step of the physics engine.
  84485. */
  84486. PhysicsEngine.prototype.getTimeStep = function () {
  84487. return this._physicsPlugin.getTimeStep();
  84488. };
  84489. PhysicsEngine.prototype.dispose = function () {
  84490. this._impostors.forEach(function (impostor) {
  84491. impostor.dispose();
  84492. });
  84493. this._physicsPlugin.dispose();
  84494. };
  84495. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  84496. return this._physicsPlugin.name;
  84497. };
  84498. /**
  84499. * Adding a new impostor for the impostor tracking.
  84500. * This will be done by the impostor itself.
  84501. * @param {PhysicsImpostor} impostor the impostor to add
  84502. */
  84503. PhysicsEngine.prototype.addImpostor = function (impostor) {
  84504. impostor.uniqueId = this._impostors.push(impostor);
  84505. //if no parent, generate the body
  84506. if (!impostor.parent) {
  84507. this._physicsPlugin.generatePhysicsBody(impostor);
  84508. }
  84509. };
  84510. /**
  84511. * Remove an impostor from the engine.
  84512. * This impostor and its mesh will not longer be updated by the physics engine.
  84513. * @param {PhysicsImpostor} impostor the impostor to remove
  84514. */
  84515. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  84516. var index = this._impostors.indexOf(impostor);
  84517. if (index > -1) {
  84518. var removed = this._impostors.splice(index, 1);
  84519. //Is it needed?
  84520. if (removed.length) {
  84521. //this will also remove it from the world.
  84522. removed[0].physicsBody = null;
  84523. }
  84524. }
  84525. };
  84526. /**
  84527. * Add a joint to the physics engine
  84528. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  84529. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  84530. * @param {PhysicsJoint} the joint that will connect both impostors.
  84531. */
  84532. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  84533. var impostorJoint = {
  84534. mainImpostor: mainImpostor,
  84535. connectedImpostor: connectedImpostor,
  84536. joint: joint
  84537. };
  84538. joint.physicsPlugin = this._physicsPlugin;
  84539. this._joints.push(impostorJoint);
  84540. this._physicsPlugin.generateJoint(impostorJoint);
  84541. };
  84542. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  84543. var matchingJoints = this._joints.filter(function (impostorJoint) {
  84544. return (impostorJoint.connectedImpostor === connectedImpostor
  84545. && impostorJoint.joint === joint
  84546. && impostorJoint.mainImpostor === mainImpostor);
  84547. });
  84548. if (matchingJoints.length) {
  84549. this._physicsPlugin.removeJoint(matchingJoints[0]);
  84550. //TODO remove it from the list as well
  84551. }
  84552. };
  84553. /**
  84554. * Called by the scene. no need to call it.
  84555. */
  84556. PhysicsEngine.prototype._step = function (delta) {
  84557. var _this = this;
  84558. //check if any mesh has no body / requires an update
  84559. this._impostors.forEach(function (impostor) {
  84560. if (impostor.isBodyInitRequired()) {
  84561. _this._physicsPlugin.generatePhysicsBody(impostor);
  84562. }
  84563. });
  84564. if (delta > 0.1) {
  84565. delta = 0.1;
  84566. }
  84567. else if (delta <= 0) {
  84568. delta = 1.0 / 60.0;
  84569. }
  84570. this._physicsPlugin.executeStep(delta, this._impostors);
  84571. };
  84572. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  84573. return this._physicsPlugin;
  84574. };
  84575. PhysicsEngine.prototype.getImpostors = function () {
  84576. return this._impostors;
  84577. };
  84578. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  84579. for (var i = 0; i < this._impostors.length; ++i) {
  84580. if (this._impostors[i].object === object) {
  84581. return this._impostors[i];
  84582. }
  84583. }
  84584. return null;
  84585. };
  84586. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  84587. for (var i = 0; i < this._impostors.length; ++i) {
  84588. if (this._impostors[i].physicsBody === body) {
  84589. return this._impostors[i];
  84590. }
  84591. }
  84592. return null;
  84593. };
  84594. // Statics
  84595. PhysicsEngine.Epsilon = 0.001;
  84596. return PhysicsEngine;
  84597. }());
  84598. BABYLON.PhysicsEngine = PhysicsEngine;
  84599. })(BABYLON || (BABYLON = {}));
  84600. //# sourceMappingURL=babylon.physicsEngine.js.map
  84601. var BABYLON;
  84602. (function (BABYLON) {
  84603. var PhysicsHelper = /** @class */ (function () {
  84604. function PhysicsHelper(scene) {
  84605. this._scene = scene;
  84606. this._physicsEngine = this._scene.getPhysicsEngine();
  84607. if (!this._physicsEngine) {
  84608. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  84609. }
  84610. }
  84611. /**
  84612. * @param {Vector3} origin the origin of the explosion
  84613. * @param {number} radius the explosion radius
  84614. * @param {number} strength the explosion strength
  84615. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84616. */
  84617. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  84618. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84619. if (!this._physicsEngine) {
  84620. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  84621. return null;
  84622. }
  84623. var impostors = this._physicsEngine.getImpostors();
  84624. if (impostors.length === 0) {
  84625. return null;
  84626. }
  84627. var event = new PhysicsRadialExplosionEvent(this._scene);
  84628. impostors.forEach(function (impostor) {
  84629. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  84630. if (!impostorForceAndContactPoint) {
  84631. return;
  84632. }
  84633. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84634. });
  84635. event.dispose(false);
  84636. return event;
  84637. };
  84638. /**
  84639. * @param {Vector3} origin the origin of the explosion
  84640. * @param {number} radius the explosion radius
  84641. * @param {number} strength the explosion strength
  84642. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84643. */
  84644. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  84645. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84646. if (!this._physicsEngine) {
  84647. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84648. return null;
  84649. }
  84650. var impostors = this._physicsEngine.getImpostors();
  84651. if (impostors.length === 0) {
  84652. return null;
  84653. }
  84654. var event = new PhysicsRadialExplosionEvent(this._scene);
  84655. impostors.forEach(function (impostor) {
  84656. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  84657. if (!impostorForceAndContactPoint) {
  84658. return;
  84659. }
  84660. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84661. });
  84662. event.dispose(false);
  84663. return event;
  84664. };
  84665. /**
  84666. * @param {Vector3} origin the origin of the explosion
  84667. * @param {number} radius the explosion radius
  84668. * @param {number} strength the explosion strength
  84669. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84670. */
  84671. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  84672. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84673. if (!this._physicsEngine) {
  84674. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84675. return null;
  84676. }
  84677. var impostors = this._physicsEngine.getImpostors();
  84678. if (impostors.length === 0) {
  84679. return null;
  84680. }
  84681. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  84682. event.dispose(false);
  84683. return event;
  84684. };
  84685. /**
  84686. * @param {Vector3} origin the origin of the updraft
  84687. * @param {number} radius the radius of the updraft
  84688. * @param {number} strength the strength of the updraft
  84689. * @param {number} height the height of the updraft
  84690. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  84691. */
  84692. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  84693. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  84694. if (!this._physicsEngine) {
  84695. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84696. return null;
  84697. }
  84698. if (this._physicsEngine.getImpostors().length === 0) {
  84699. return null;
  84700. }
  84701. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  84702. event.dispose(false);
  84703. return event;
  84704. };
  84705. /**
  84706. * @param {Vector3} origin the of the vortex
  84707. * @param {number} radius the radius of the vortex
  84708. * @param {number} strength the strength of the vortex
  84709. * @param {number} height the height of the vortex
  84710. */
  84711. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  84712. if (!this._physicsEngine) {
  84713. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84714. return null;
  84715. }
  84716. if (this._physicsEngine.getImpostors().length === 0) {
  84717. return null;
  84718. }
  84719. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  84720. event.dispose(false);
  84721. return event;
  84722. };
  84723. return PhysicsHelper;
  84724. }());
  84725. BABYLON.PhysicsHelper = PhysicsHelper;
  84726. /***** Radial explosion *****/
  84727. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  84728. function PhysicsRadialExplosionEvent(scene) {
  84729. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  84730. this._rays = [];
  84731. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  84732. this._scene = scene;
  84733. }
  84734. /**
  84735. * Returns the data related to the radial explosion event (sphere & rays).
  84736. * @returns {PhysicsRadialExplosionEventData}
  84737. */
  84738. PhysicsRadialExplosionEvent.prototype.getData = function () {
  84739. this._dataFetched = true;
  84740. return {
  84741. sphere: this._sphere,
  84742. rays: this._rays,
  84743. };
  84744. };
  84745. /**
  84746. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  84747. * @param impostor
  84748. * @param {Vector3} origin the origin of the explosion
  84749. * @param {number} radius the explosion radius
  84750. * @param {number} strength the explosion strength
  84751. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  84752. * @returns {Nullable<PhysicsForceAndContactPoint>}
  84753. */
  84754. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  84755. if (impostor.mass === 0) {
  84756. return null;
  84757. }
  84758. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  84759. return null;
  84760. }
  84761. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84762. return null;
  84763. }
  84764. var impostorObjectCenter = impostor.getObjectCenter();
  84765. var direction = impostorObjectCenter.subtract(origin);
  84766. var ray = new BABYLON.Ray(origin, direction, radius);
  84767. this._rays.push(ray);
  84768. var hit = ray.intersectsMesh(impostor.object);
  84769. var contactPoint = hit.pickedPoint;
  84770. if (!contactPoint) {
  84771. return null;
  84772. }
  84773. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  84774. if (distanceFromOrigin > radius) {
  84775. return null;
  84776. }
  84777. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  84778. ? strength
  84779. : strength * (1 - (distanceFromOrigin / radius));
  84780. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84781. return { force: force, contactPoint: contactPoint };
  84782. };
  84783. /**
  84784. * Disposes the sphere.
  84785. * @param {bolean} force
  84786. */
  84787. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  84788. var _this = this;
  84789. if (force === void 0) { force = true; }
  84790. if (force) {
  84791. this._sphere.dispose();
  84792. }
  84793. else {
  84794. setTimeout(function () {
  84795. if (!_this._dataFetched) {
  84796. _this._sphere.dispose();
  84797. }
  84798. }, 0);
  84799. }
  84800. };
  84801. /*** Helpers ***/
  84802. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  84803. if (!this._sphere) {
  84804. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  84805. this._sphere.isVisible = false;
  84806. }
  84807. };
  84808. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  84809. var impostorObject = impostor.object;
  84810. this._prepareSphere();
  84811. this._sphere.position = origin;
  84812. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  84813. this._sphere._updateBoundingInfo();
  84814. this._sphere.computeWorldMatrix(true);
  84815. return this._sphere.intersectsMesh(impostorObject, true);
  84816. };
  84817. return PhysicsRadialExplosionEvent;
  84818. }());
  84819. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  84820. /***** Gravitational Field *****/
  84821. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  84822. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  84823. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84824. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84825. this._physicsHelper = physicsHelper;
  84826. this._scene = scene;
  84827. this._origin = origin;
  84828. this._radius = radius;
  84829. this._strength = strength;
  84830. this._falloff = falloff;
  84831. this._tickCallback = this._tick.bind(this);
  84832. }
  84833. /**
  84834. * Returns the data related to the gravitational field event (sphere).
  84835. * @returns {PhysicsGravitationalFieldEventData}
  84836. */
  84837. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  84838. this._dataFetched = true;
  84839. return {
  84840. sphere: this._sphere,
  84841. };
  84842. };
  84843. /**
  84844. * Enables the gravitational field.
  84845. */
  84846. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  84847. this._tickCallback.call(this);
  84848. this._scene.registerBeforeRender(this._tickCallback);
  84849. };
  84850. /**
  84851. * Disables the gravitational field.
  84852. */
  84853. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  84854. this._scene.unregisterBeforeRender(this._tickCallback);
  84855. };
  84856. /**
  84857. * Disposes the sphere.
  84858. * @param {bolean} force
  84859. */
  84860. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  84861. var _this = this;
  84862. if (force === void 0) { force = true; }
  84863. if (force) {
  84864. this._sphere.dispose();
  84865. }
  84866. else {
  84867. setTimeout(function () {
  84868. if (!_this._dataFetched) {
  84869. _this._sphere.dispose();
  84870. }
  84871. }, 0);
  84872. }
  84873. };
  84874. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  84875. // Since the params won't change, we fetch the event only once
  84876. if (this._sphere) {
  84877. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84878. }
  84879. else {
  84880. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84881. if (radialExplosionEvent) {
  84882. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  84883. }
  84884. }
  84885. };
  84886. return PhysicsGravitationalFieldEvent;
  84887. }());
  84888. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  84889. /***** Updraft *****/
  84890. var PhysicsUpdraftEvent = /** @class */ (function () {
  84891. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  84892. this._scene = _scene;
  84893. this._origin = _origin;
  84894. this._radius = _radius;
  84895. this._strength = _strength;
  84896. this._height = _height;
  84897. this._updraftMode = _updraftMode;
  84898. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84899. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  84900. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84901. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84902. this._physicsEngine = this._scene.getPhysicsEngine();
  84903. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84904. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84905. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84906. this._originDirection = this._origin.subtract(this._originTop).normalize();
  84907. }
  84908. this._tickCallback = this._tick.bind(this);
  84909. }
  84910. /**
  84911. * Returns the data related to the updraft event (cylinder).
  84912. * @returns {PhysicsUpdraftEventData}
  84913. */
  84914. PhysicsUpdraftEvent.prototype.getData = function () {
  84915. this._dataFetched = true;
  84916. return {
  84917. cylinder: this._cylinder,
  84918. };
  84919. };
  84920. /**
  84921. * Enables the updraft.
  84922. */
  84923. PhysicsUpdraftEvent.prototype.enable = function () {
  84924. this._tickCallback.call(this);
  84925. this._scene.registerBeforeRender(this._tickCallback);
  84926. };
  84927. /**
  84928. * Disables the cortex.
  84929. */
  84930. PhysicsUpdraftEvent.prototype.disable = function () {
  84931. this._scene.unregisterBeforeRender(this._tickCallback);
  84932. };
  84933. /**
  84934. * Disposes the sphere.
  84935. * @param {bolean} force
  84936. */
  84937. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  84938. var _this = this;
  84939. if (force === void 0) { force = true; }
  84940. if (force) {
  84941. this._cylinder.dispose();
  84942. }
  84943. else {
  84944. setTimeout(function () {
  84945. if (!_this._dataFetched) {
  84946. _this._cylinder.dispose();
  84947. }
  84948. }, 0);
  84949. }
  84950. };
  84951. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84952. if (impostor.mass === 0) {
  84953. return null;
  84954. }
  84955. if (!this._intersectsWithCylinder(impostor)) {
  84956. return null;
  84957. }
  84958. var impostorObjectCenter = impostor.getObjectCenter();
  84959. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84960. var direction = this._originDirection;
  84961. }
  84962. else {
  84963. var direction = impostorObjectCenter.subtract(this._originTop);
  84964. }
  84965. var multiplier = this._strength * -1;
  84966. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84967. return { force: force, contactPoint: impostorObjectCenter };
  84968. };
  84969. PhysicsUpdraftEvent.prototype._tick = function () {
  84970. var _this = this;
  84971. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84972. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84973. if (!impostorForceAndContactPoint) {
  84974. return;
  84975. }
  84976. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84977. });
  84978. };
  84979. /*** Helpers ***/
  84980. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  84981. if (!this._cylinder) {
  84982. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  84983. height: this._height,
  84984. diameter: this._radius * 2,
  84985. }, this._scene);
  84986. this._cylinder.isVisible = false;
  84987. }
  84988. };
  84989. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  84990. var impostorObject = impostor.object;
  84991. this._prepareCylinder();
  84992. this._cylinder.position = this._cylinderPosition;
  84993. return this._cylinder.intersectsMesh(impostorObject, true);
  84994. };
  84995. return PhysicsUpdraftEvent;
  84996. }());
  84997. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  84998. /***** Vortex *****/
  84999. var PhysicsVortexEvent = /** @class */ (function () {
  85000. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  85001. this._scene = _scene;
  85002. this._origin = _origin;
  85003. this._radius = _radius;
  85004. this._strength = _strength;
  85005. this._height = _height;
  85006. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85007. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  85008. this._updraftMultiplier = 0.02;
  85009. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85010. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85011. this._physicsEngine = this._scene.getPhysicsEngine();
  85012. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85013. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85014. this._tickCallback = this._tick.bind(this);
  85015. }
  85016. /**
  85017. * Returns the data related to the vortex event (cylinder).
  85018. * @returns {PhysicsVortexEventData}
  85019. */
  85020. PhysicsVortexEvent.prototype.getData = function () {
  85021. this._dataFetched = true;
  85022. return {
  85023. cylinder: this._cylinder,
  85024. };
  85025. };
  85026. /**
  85027. * Enables the vortex.
  85028. */
  85029. PhysicsVortexEvent.prototype.enable = function () {
  85030. this._tickCallback.call(this);
  85031. this._scene.registerBeforeRender(this._tickCallback);
  85032. };
  85033. /**
  85034. * Disables the cortex.
  85035. */
  85036. PhysicsVortexEvent.prototype.disable = function () {
  85037. this._scene.unregisterBeforeRender(this._tickCallback);
  85038. };
  85039. /**
  85040. * Disposes the sphere.
  85041. * @param {bolean} force
  85042. */
  85043. PhysicsVortexEvent.prototype.dispose = function (force) {
  85044. var _this = this;
  85045. if (force === void 0) { force = true; }
  85046. if (force) {
  85047. this._cylinder.dispose();
  85048. }
  85049. else {
  85050. setTimeout(function () {
  85051. if (!_this._dataFetched) {
  85052. _this._cylinder.dispose();
  85053. }
  85054. }, 0);
  85055. }
  85056. };
  85057. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85058. if (impostor.mass === 0) {
  85059. return null;
  85060. }
  85061. if (!this._intersectsWithCylinder(impostor)) {
  85062. return null;
  85063. }
  85064. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85065. return null;
  85066. }
  85067. var impostorObjectCenter = impostor.getObjectCenter();
  85068. 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)
  85069. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  85070. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  85071. var hit = ray.intersectsMesh(impostor.object);
  85072. var contactPoint = hit.pickedPoint;
  85073. if (!contactPoint) {
  85074. return null;
  85075. }
  85076. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  85077. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  85078. var directionToOrigin = contactPoint.normalize();
  85079. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85080. directionToOrigin = directionToOrigin.negate();
  85081. }
  85082. // TODO: find a more physically based solution
  85083. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85084. var forceX = directionToOrigin.x * this._strength / 8;
  85085. var forceY = directionToOrigin.y * this._updraftMultiplier;
  85086. var forceZ = directionToOrigin.z * this._strength / 8;
  85087. }
  85088. else {
  85089. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  85090. var forceY = this._originTop.y * this._updraftMultiplier;
  85091. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  85092. }
  85093. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  85094. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  85095. return { force: force, contactPoint: impostorObjectCenter };
  85096. };
  85097. PhysicsVortexEvent.prototype._tick = function () {
  85098. var _this = this;
  85099. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85100. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85101. if (!impostorForceAndContactPoint) {
  85102. return;
  85103. }
  85104. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85105. });
  85106. };
  85107. /*** Helpers ***/
  85108. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  85109. if (!this._cylinder) {
  85110. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  85111. height: this._height,
  85112. diameter: this._radius * 2,
  85113. }, this._scene);
  85114. this._cylinder.isVisible = false;
  85115. }
  85116. };
  85117. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  85118. var impostorObject = impostor.object;
  85119. this._prepareCylinder();
  85120. this._cylinder.position = this._cylinderPosition;
  85121. return this._cylinder.intersectsMesh(impostorObject, true);
  85122. };
  85123. return PhysicsVortexEvent;
  85124. }());
  85125. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  85126. /***** Enums *****/
  85127. /**
  85128. * The strenght of the force in correspondence to the distance of the affected object
  85129. */
  85130. var PhysicsRadialImpulseFalloff;
  85131. (function (PhysicsRadialImpulseFalloff) {
  85132. /** Defines that impulse is constant in strength across it's whole radius */
  85133. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  85134. /** DEfines that impulse gets weaker if it's further from the origin */
  85135. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  85136. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  85137. /**
  85138. * The strenght of the force in correspondence to the distance of the affected object
  85139. */
  85140. var PhysicsUpdraftMode;
  85141. (function (PhysicsUpdraftMode) {
  85142. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  85143. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  85144. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  85145. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  85146. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  85147. })(BABYLON || (BABYLON = {}));
  85148. //# sourceMappingURL=babylon.physicsHelper.js.map
  85149. var BABYLON;
  85150. (function (BABYLON) {
  85151. var CannonJSPlugin = /** @class */ (function () {
  85152. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  85153. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  85154. if (iterations === void 0) { iterations = 10; }
  85155. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  85156. this.name = "CannonJSPlugin";
  85157. this._physicsMaterials = new Array();
  85158. this._fixedTimeStep = 1 / 60;
  85159. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  85160. this.BJSCANNON = CANNON;
  85161. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  85162. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  85163. this._tmpPosition = BABYLON.Vector3.Zero();
  85164. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  85165. this._tmpUnityRotation = new BABYLON.Quaternion();
  85166. if (!this.isSupported()) {
  85167. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  85168. return;
  85169. }
  85170. this._extendNamespace();
  85171. this.world = new this.BJSCANNON.World();
  85172. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  85173. this.world.solver.iterations = iterations;
  85174. }
  85175. CannonJSPlugin.prototype.setGravity = function (gravity) {
  85176. this.world.gravity.copy(gravity);
  85177. };
  85178. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  85179. this._fixedTimeStep = timeStep;
  85180. };
  85181. CannonJSPlugin.prototype.getTimeStep = function () {
  85182. return this._fixedTimeStep;
  85183. };
  85184. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  85185. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  85186. };
  85187. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85188. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85189. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85190. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  85191. };
  85192. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85193. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85194. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85195. impostor.physicsBody.applyForce(impulse, worldPoint);
  85196. };
  85197. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85198. //parent-child relationship. Does this impostor has a parent impostor?
  85199. if (impostor.parent) {
  85200. if (impostor.physicsBody) {
  85201. this.removePhysicsBody(impostor);
  85202. //TODO is that needed?
  85203. impostor.forceUpdate();
  85204. }
  85205. return;
  85206. }
  85207. //should a new body be created for this impostor?
  85208. if (impostor.isBodyInitRequired()) {
  85209. var shape = this._createShape(impostor);
  85210. //unregister events, if body is being changed
  85211. var oldBody = impostor.physicsBody;
  85212. if (oldBody) {
  85213. this.removePhysicsBody(impostor);
  85214. }
  85215. //create the body and material
  85216. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  85217. var bodyCreationObject = {
  85218. mass: impostor.getParam("mass"),
  85219. material: material
  85220. };
  85221. // A simple extend, in case native options were used.
  85222. var nativeOptions = impostor.getParam("nativeOptions");
  85223. for (var key in nativeOptions) {
  85224. if (nativeOptions.hasOwnProperty(key)) {
  85225. bodyCreationObject[key] = nativeOptions[key];
  85226. }
  85227. }
  85228. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  85229. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  85230. this.world.addEventListener("preStep", impostor.beforeStep);
  85231. this.world.addEventListener("postStep", impostor.afterStep);
  85232. impostor.physicsBody.addShape(shape);
  85233. this.world.add(impostor.physicsBody);
  85234. //try to keep the body moving in the right direction by taking old properties.
  85235. //Should be tested!
  85236. if (oldBody) {
  85237. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  85238. impostor.physicsBody[param].copy(oldBody[param]);
  85239. });
  85240. }
  85241. this._processChildMeshes(impostor);
  85242. }
  85243. //now update the body's transformation
  85244. this._updatePhysicsBodyTransformation(impostor);
  85245. };
  85246. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  85247. var _this = this;
  85248. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  85249. var currentRotation = mainImpostor.object.rotationQuaternion;
  85250. if (meshChildren.length) {
  85251. var processMesh = function (localPosition, mesh) {
  85252. if (!currentRotation || !mesh.rotationQuaternion) {
  85253. return;
  85254. }
  85255. var childImpostor = mesh.getPhysicsImpostor();
  85256. if (childImpostor) {
  85257. var parent = childImpostor.parent;
  85258. if (parent !== mainImpostor) {
  85259. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  85260. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  85261. if (childImpostor.physicsBody) {
  85262. _this.removePhysicsBody(childImpostor);
  85263. childImpostor.physicsBody = null;
  85264. }
  85265. childImpostor.parent = mainImpostor;
  85266. childImpostor.resetUpdateFlags();
  85267. 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));
  85268. //Add the mass of the children.
  85269. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  85270. }
  85271. }
  85272. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  85273. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  85274. };
  85275. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  85276. }
  85277. };
  85278. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85279. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  85280. this.world.removeEventListener("preStep", impostor.beforeStep);
  85281. this.world.removeEventListener("postStep", impostor.afterStep);
  85282. this.world.remove(impostor.physicsBody);
  85283. };
  85284. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85285. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85286. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85287. if (!mainBody || !connectedBody) {
  85288. return;
  85289. }
  85290. var constraint;
  85291. var jointData = impostorJoint.joint.jointData;
  85292. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  85293. var constraintData = {
  85294. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  85295. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  85296. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  85297. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  85298. maxForce: jointData.nativeParams.maxForce,
  85299. collideConnected: !!jointData.collision
  85300. };
  85301. switch (impostorJoint.joint.type) {
  85302. case BABYLON.PhysicsJoint.HingeJoint:
  85303. case BABYLON.PhysicsJoint.Hinge2Joint:
  85304. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  85305. break;
  85306. case BABYLON.PhysicsJoint.DistanceJoint:
  85307. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  85308. break;
  85309. case BABYLON.PhysicsJoint.SpringJoint:
  85310. var springData = jointData;
  85311. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  85312. restLength: springData.length,
  85313. stiffness: springData.stiffness,
  85314. damping: springData.damping,
  85315. localAnchorA: constraintData.pivotA,
  85316. localAnchorB: constraintData.pivotB
  85317. });
  85318. break;
  85319. case BABYLON.PhysicsJoint.LockJoint:
  85320. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  85321. break;
  85322. case BABYLON.PhysicsJoint.PointToPointJoint:
  85323. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85324. default:
  85325. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  85326. break;
  85327. }
  85328. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  85329. constraint.collideConnected = !!jointData.collision;
  85330. impostorJoint.joint.physicsJoint = constraint;
  85331. //don't add spring as constraint, as it is not one.
  85332. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  85333. this.world.addConstraint(constraint);
  85334. }
  85335. else {
  85336. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  85337. constraint.applyForce();
  85338. });
  85339. }
  85340. };
  85341. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85342. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  85343. };
  85344. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  85345. var index;
  85346. var mat;
  85347. for (index = 0; index < this._physicsMaterials.length; index++) {
  85348. mat = this._physicsMaterials[index];
  85349. if (mat.friction === friction && mat.restitution === restitution) {
  85350. return mat;
  85351. }
  85352. }
  85353. var currentMat = new this.BJSCANNON.Material(name);
  85354. currentMat.friction = friction;
  85355. currentMat.restitution = restitution;
  85356. this._physicsMaterials.push(currentMat);
  85357. return currentMat;
  85358. };
  85359. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  85360. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  85361. };
  85362. CannonJSPlugin.prototype._createShape = function (impostor) {
  85363. var object = impostor.object;
  85364. var returnValue;
  85365. var extendSize = impostor.getObjectExtendSize();
  85366. switch (impostor.type) {
  85367. case BABYLON.PhysicsImpostor.SphereImpostor:
  85368. var radiusX = extendSize.x;
  85369. var radiusY = extendSize.y;
  85370. var radiusZ = extendSize.z;
  85371. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  85372. break;
  85373. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  85374. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85375. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  85376. break;
  85377. case BABYLON.PhysicsImpostor.BoxImpostor:
  85378. var box = extendSize.scale(0.5);
  85379. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  85380. break;
  85381. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85382. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  85383. returnValue = new this.BJSCANNON.Plane();
  85384. break;
  85385. case BABYLON.PhysicsImpostor.MeshImpostor:
  85386. // should transform the vertex data to world coordinates!!
  85387. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  85388. var rawFaces = object.getIndices ? object.getIndices() : [];
  85389. if (!rawVerts)
  85390. return;
  85391. // get only scale! so the object could transform correctly.
  85392. var oldPosition = object.position.clone();
  85393. var oldRotation = object.rotation && object.rotation.clone();
  85394. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  85395. object.position.copyFromFloats(0, 0, 0);
  85396. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  85397. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  85398. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  85399. var transform = object.computeWorldMatrix(true);
  85400. // convert rawVerts to object space
  85401. var temp = new Array();
  85402. var index;
  85403. for (index = 0; index < rawVerts.length; index += 3) {
  85404. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  85405. }
  85406. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  85407. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  85408. //now set back the transformation!
  85409. object.position.copyFrom(oldPosition);
  85410. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  85411. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  85412. break;
  85413. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  85414. var oldPosition2 = object.position.clone();
  85415. var oldRotation2 = object.rotation && object.rotation.clone();
  85416. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  85417. object.position.copyFromFloats(0, 0, 0);
  85418. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  85419. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  85420. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  85421. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  85422. returnValue = this._createHeightmap(object);
  85423. object.position.copyFrom(oldPosition2);
  85424. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  85425. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  85426. object.computeWorldMatrix(true);
  85427. break;
  85428. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85429. returnValue = new this.BJSCANNON.Particle();
  85430. break;
  85431. }
  85432. return returnValue;
  85433. };
  85434. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  85435. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85436. var transform = object.computeWorldMatrix(true);
  85437. // convert rawVerts to object space
  85438. var temp = new Array();
  85439. var index;
  85440. for (index = 0; index < pos.length; index += 3) {
  85441. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  85442. }
  85443. pos = temp;
  85444. var matrix = new Array();
  85445. //For now pointDepth will not be used and will be automatically calculated.
  85446. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  85447. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  85448. var boundingInfo = object.getBoundingInfo();
  85449. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  85450. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  85451. var elementSize = dim * 2 / arraySize;
  85452. for (var i = 0; i < pos.length; i = i + 3) {
  85453. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  85454. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  85455. var y = -pos[i + 2] + minY;
  85456. if (!matrix[x]) {
  85457. matrix[x] = [];
  85458. }
  85459. if (!matrix[x][z]) {
  85460. matrix[x][z] = y;
  85461. }
  85462. matrix[x][z] = Math.max(y, matrix[x][z]);
  85463. }
  85464. for (var x = 0; x <= arraySize; ++x) {
  85465. if (!matrix[x]) {
  85466. var loc = 1;
  85467. while (!matrix[(x + loc) % arraySize]) {
  85468. loc++;
  85469. }
  85470. matrix[x] = matrix[(x + loc) % arraySize].slice();
  85471. //console.log("missing x", x);
  85472. }
  85473. for (var z = 0; z <= arraySize; ++z) {
  85474. if (!matrix[x][z]) {
  85475. var loc = 1;
  85476. var newValue;
  85477. while (newValue === undefined) {
  85478. newValue = matrix[x][(z + loc++) % arraySize];
  85479. }
  85480. matrix[x][z] = newValue;
  85481. }
  85482. }
  85483. }
  85484. var shape = new this.BJSCANNON.Heightfield(matrix, {
  85485. elementSize: elementSize
  85486. });
  85487. //For future reference, needed for body transformation
  85488. shape.minY = minY;
  85489. return shape;
  85490. };
  85491. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  85492. var object = impostor.object;
  85493. //make sure it is updated...
  85494. object.computeWorldMatrix && object.computeWorldMatrix(true);
  85495. // The delta between the mesh position and the mesh bounding box center
  85496. var bInfo = object.getBoundingInfo();
  85497. if (!bInfo)
  85498. return;
  85499. var center = impostor.getObjectCenter();
  85500. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  85501. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  85502. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  85503. this._tmpPosition.copyFrom(center);
  85504. var quaternion = object.rotationQuaternion;
  85505. if (!quaternion) {
  85506. return;
  85507. }
  85508. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  85509. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  85510. //-90 DEG in X, precalculated
  85511. quaternion = quaternion.multiply(this._minus90X);
  85512. //Invert! (Precalculated, 90 deg in X)
  85513. //No need to clone. this will never change.
  85514. impostor.setDeltaRotation(this._plus90X);
  85515. }
  85516. //If it is a heightfield, if should be centered.
  85517. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  85518. var mesh = object;
  85519. var boundingInfo = mesh.getBoundingInfo();
  85520. //calculate the correct body position:
  85521. var rotationQuaternion = mesh.rotationQuaternion;
  85522. mesh.rotationQuaternion = this._tmpUnityRotation;
  85523. mesh.computeWorldMatrix(true);
  85524. //get original center with no rotation
  85525. var c = center.clone();
  85526. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  85527. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  85528. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  85529. mesh.setPreTransformMatrix(p);
  85530. mesh.computeWorldMatrix(true);
  85531. //calculate the translation
  85532. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  85533. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  85534. //add it inverted to the delta
  85535. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  85536. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  85537. //rotation is back
  85538. mesh.rotationQuaternion = rotationQuaternion;
  85539. mesh.setPreTransformMatrix(oldPivot);
  85540. mesh.computeWorldMatrix(true);
  85541. }
  85542. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  85543. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  85544. //this._tmpPosition.copyFrom(object.position);
  85545. }
  85546. impostor.setDeltaPosition(this._tmpDeltaPosition);
  85547. //Now update the impostor object
  85548. impostor.physicsBody.position.copy(this._tmpPosition);
  85549. impostor.physicsBody.quaternion.copy(quaternion);
  85550. };
  85551. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  85552. impostor.object.position.copyFrom(impostor.physicsBody.position);
  85553. if (impostor.object.rotationQuaternion) {
  85554. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  85555. }
  85556. };
  85557. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  85558. impostor.physicsBody.position.copy(newPosition);
  85559. impostor.physicsBody.quaternion.copy(newRotation);
  85560. };
  85561. CannonJSPlugin.prototype.isSupported = function () {
  85562. return this.BJSCANNON !== undefined;
  85563. };
  85564. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  85565. impostor.physicsBody.velocity.copy(velocity);
  85566. };
  85567. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  85568. impostor.physicsBody.angularVelocity.copy(velocity);
  85569. };
  85570. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  85571. var v = impostor.physicsBody.velocity;
  85572. if (!v) {
  85573. return null;
  85574. }
  85575. return new BABYLON.Vector3(v.x, v.y, v.z);
  85576. };
  85577. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  85578. var v = impostor.physicsBody.angularVelocity;
  85579. if (!v) {
  85580. return null;
  85581. }
  85582. return new BABYLON.Vector3(v.x, v.y, v.z);
  85583. };
  85584. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  85585. impostor.physicsBody.mass = mass;
  85586. impostor.physicsBody.updateMassProperties();
  85587. };
  85588. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  85589. return impostor.physicsBody.mass;
  85590. };
  85591. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  85592. return impostor.physicsBody.material.friction;
  85593. };
  85594. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  85595. impostor.physicsBody.material.friction = friction;
  85596. };
  85597. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  85598. return impostor.physicsBody.material.restitution;
  85599. };
  85600. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  85601. impostor.physicsBody.material.restitution = restitution;
  85602. };
  85603. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  85604. impostor.physicsBody.sleep();
  85605. };
  85606. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  85607. impostor.physicsBody.wakeUp();
  85608. };
  85609. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  85610. joint.physicsJoint.distance = maxDistance;
  85611. };
  85612. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  85613. // if (!motorIndex) {
  85614. // joint.physicsJoint.enableMotor();
  85615. // }
  85616. // }
  85617. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  85618. // if (!motorIndex) {
  85619. // joint.physicsJoint.disableMotor();
  85620. // }
  85621. // }
  85622. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  85623. if (!motorIndex) {
  85624. joint.physicsJoint.enableMotor();
  85625. joint.physicsJoint.setMotorSpeed(speed);
  85626. if (maxForce) {
  85627. this.setLimit(joint, maxForce);
  85628. }
  85629. }
  85630. };
  85631. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  85632. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  85633. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  85634. };
  85635. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  85636. var body = impostor.physicsBody;
  85637. mesh.position.x = body.position.x;
  85638. mesh.position.y = body.position.y;
  85639. mesh.position.z = body.position.z;
  85640. if (mesh.rotationQuaternion) {
  85641. mesh.rotationQuaternion.x = body.quaternion.x;
  85642. mesh.rotationQuaternion.y = body.quaternion.y;
  85643. mesh.rotationQuaternion.z = body.quaternion.z;
  85644. mesh.rotationQuaternion.w = body.quaternion.w;
  85645. }
  85646. };
  85647. CannonJSPlugin.prototype.getRadius = function (impostor) {
  85648. var shape = impostor.physicsBody.shapes[0];
  85649. return shape.boundingSphereRadius;
  85650. };
  85651. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  85652. var shape = impostor.physicsBody.shapes[0];
  85653. result.x = shape.halfExtents.x * 2;
  85654. result.y = shape.halfExtents.y * 2;
  85655. result.z = shape.halfExtents.z * 2;
  85656. };
  85657. CannonJSPlugin.prototype.dispose = function () {
  85658. };
  85659. CannonJSPlugin.prototype._extendNamespace = function () {
  85660. //this will force cannon to execute at least one step when using interpolation
  85661. var step_tmp1 = new this.BJSCANNON.Vec3();
  85662. var Engine = this.BJSCANNON;
  85663. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  85664. maxSubSteps = maxSubSteps || 10;
  85665. timeSinceLastCalled = timeSinceLastCalled || 0;
  85666. if (timeSinceLastCalled === 0) {
  85667. this.internalStep(dt);
  85668. this.time += dt;
  85669. }
  85670. else {
  85671. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  85672. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  85673. var t0 = performance.now();
  85674. for (var i = 0; i !== internalSteps; i++) {
  85675. this.internalStep(dt);
  85676. if (performance.now() - t0 > dt * 1000) {
  85677. break;
  85678. }
  85679. }
  85680. this.time += timeSinceLastCalled;
  85681. var h = this.time % dt;
  85682. var h_div_dt = h / dt;
  85683. var interpvelo = step_tmp1;
  85684. var bodies = this.bodies;
  85685. for (var j = 0; j !== bodies.length; j++) {
  85686. var b = bodies[j];
  85687. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  85688. b.position.vsub(b.previousPosition, interpvelo);
  85689. interpvelo.scale(h_div_dt, interpvelo);
  85690. b.position.vadd(interpvelo, b.interpolatedPosition);
  85691. }
  85692. else {
  85693. b.interpolatedPosition.copy(b.position);
  85694. b.interpolatedQuaternion.copy(b.quaternion);
  85695. }
  85696. }
  85697. }
  85698. };
  85699. };
  85700. return CannonJSPlugin;
  85701. }());
  85702. BABYLON.CannonJSPlugin = CannonJSPlugin;
  85703. })(BABYLON || (BABYLON = {}));
  85704. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  85705. var BABYLON;
  85706. (function (BABYLON) {
  85707. var OimoJSPlugin = /** @class */ (function () {
  85708. function OimoJSPlugin(iterations) {
  85709. this.name = "OimoJSPlugin";
  85710. this._tmpImpostorsArray = [];
  85711. this._tmpPositionVector = BABYLON.Vector3.Zero();
  85712. this.BJSOIMO = OIMO;
  85713. this.world = new this.BJSOIMO.World({
  85714. iterations: iterations
  85715. });
  85716. this.world.clear();
  85717. }
  85718. OimoJSPlugin.prototype.setGravity = function (gravity) {
  85719. this.world.gravity.copy(gravity);
  85720. };
  85721. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  85722. this.world.timeStep = timeStep;
  85723. };
  85724. OimoJSPlugin.prototype.getTimeStep = function () {
  85725. return this.world.timeStep;
  85726. };
  85727. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  85728. var _this = this;
  85729. impostors.forEach(function (impostor) {
  85730. impostor.beforeStep();
  85731. });
  85732. this.world.step();
  85733. impostors.forEach(function (impostor) {
  85734. impostor.afterStep();
  85735. //update the ordered impostors array
  85736. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  85737. });
  85738. //check for collisions
  85739. var contact = this.world.contacts;
  85740. while (contact !== null) {
  85741. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  85742. contact = contact.next;
  85743. continue;
  85744. }
  85745. //is this body colliding with any other? get the impostor
  85746. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  85747. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  85748. if (!mainImpostor || !collidingImpostor) {
  85749. contact = contact.next;
  85750. continue;
  85751. }
  85752. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  85753. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  85754. contact = contact.next;
  85755. }
  85756. };
  85757. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85758. var mass = impostor.physicsBody.mass;
  85759. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  85760. };
  85761. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85762. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  85763. this.applyImpulse(impostor, force, contactPoint);
  85764. };
  85765. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85766. var _this = this;
  85767. //parent-child relationship. Does this impostor has a parent impostor?
  85768. if (impostor.parent) {
  85769. if (impostor.physicsBody) {
  85770. this.removePhysicsBody(impostor);
  85771. //TODO is that needed?
  85772. impostor.forceUpdate();
  85773. }
  85774. return;
  85775. }
  85776. if (impostor.isBodyInitRequired()) {
  85777. var bodyConfig = {
  85778. name: impostor.uniqueId,
  85779. //Oimo must have mass, also for static objects.
  85780. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  85781. size: [],
  85782. type: [],
  85783. pos: [],
  85784. posShape: [],
  85785. rot: [],
  85786. rotShape: [],
  85787. move: impostor.getParam("mass") !== 0,
  85788. density: impostor.getParam("mass"),
  85789. friction: impostor.getParam("friction"),
  85790. restitution: impostor.getParam("restitution"),
  85791. //Supporting older versions of Oimo
  85792. world: this.world
  85793. };
  85794. var impostors = [impostor];
  85795. var addToArray = function (parent) {
  85796. if (!parent.getChildMeshes)
  85797. return;
  85798. parent.getChildMeshes().forEach(function (m) {
  85799. if (m.physicsImpostor) {
  85800. impostors.push(m.physicsImpostor);
  85801. //m.physicsImpostor._init();
  85802. }
  85803. });
  85804. };
  85805. addToArray(impostor.object);
  85806. var checkWithEpsilon_1 = function (value) {
  85807. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  85808. };
  85809. impostors.forEach(function (i) {
  85810. if (!i.object.rotationQuaternion) {
  85811. return;
  85812. }
  85813. //get the correct bounding box
  85814. var oldQuaternion = i.object.rotationQuaternion;
  85815. var rot = oldQuaternion.toEulerAngles();
  85816. var extendSize = i.getObjectExtendSize();
  85817. var radToDeg = 57.295779513082320876;
  85818. if (i === impostor) {
  85819. var center = impostor.getObjectCenter();
  85820. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  85821. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  85822. //Can also use Array.prototype.push.apply
  85823. bodyConfig.pos.push(center.x);
  85824. bodyConfig.pos.push(center.y);
  85825. bodyConfig.pos.push(center.z);
  85826. bodyConfig.posShape.push(0, 0, 0);
  85827. //tmp solution
  85828. bodyConfig.rot.push(rot.x * radToDeg);
  85829. bodyConfig.rot.push(rot.y * radToDeg);
  85830. bodyConfig.rot.push(rot.z * radToDeg);
  85831. bodyConfig.rotShape.push(0, 0, 0);
  85832. }
  85833. else {
  85834. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  85835. bodyConfig.posShape.push(localPosition.x);
  85836. bodyConfig.posShape.push(localPosition.y);
  85837. bodyConfig.posShape.push(localPosition.z);
  85838. bodyConfig.pos.push(0, 0, 0);
  85839. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  85840. bodyConfig.rot.push(0);
  85841. bodyConfig.rot.push(0);
  85842. bodyConfig.rot.push(0);
  85843. bodyConfig.rotShape.push(rot.x * radToDeg);
  85844. bodyConfig.rotShape.push(rot.y * radToDeg);
  85845. bodyConfig.rotShape.push(rot.z * radToDeg);
  85846. }
  85847. // register mesh
  85848. switch (i.type) {
  85849. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85850. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  85851. case BABYLON.PhysicsImpostor.SphereImpostor:
  85852. var radiusX = extendSize.x;
  85853. var radiusY = extendSize.y;
  85854. var radiusZ = extendSize.z;
  85855. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  85856. bodyConfig.type.push('sphere');
  85857. //due to the way oimo works with compounds, add 3 times
  85858. bodyConfig.size.push(size);
  85859. bodyConfig.size.push(size);
  85860. bodyConfig.size.push(size);
  85861. break;
  85862. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85863. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  85864. var sizeY = checkWithEpsilon_1(extendSize.y);
  85865. bodyConfig.type.push('cylinder');
  85866. bodyConfig.size.push(sizeX);
  85867. bodyConfig.size.push(sizeY);
  85868. //due to the way oimo works with compounds, add one more value.
  85869. bodyConfig.size.push(sizeY);
  85870. break;
  85871. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85872. case BABYLON.PhysicsImpostor.BoxImpostor:
  85873. default:
  85874. var sizeX = checkWithEpsilon_1(extendSize.x);
  85875. var sizeY = checkWithEpsilon_1(extendSize.y);
  85876. var sizeZ = checkWithEpsilon_1(extendSize.z);
  85877. bodyConfig.type.push('box');
  85878. //if (i === impostor) {
  85879. bodyConfig.size.push(sizeX);
  85880. bodyConfig.size.push(sizeY);
  85881. bodyConfig.size.push(sizeZ);
  85882. //} else {
  85883. // bodyConfig.size.push(0,0,0);
  85884. //}
  85885. break;
  85886. }
  85887. //actually not needed, but hey...
  85888. i.object.rotationQuaternion = oldQuaternion;
  85889. });
  85890. impostor.physicsBody = this.world.add(bodyConfig);
  85891. }
  85892. else {
  85893. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  85894. }
  85895. impostor.setDeltaPosition(this._tmpPositionVector);
  85896. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  85897. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  85898. };
  85899. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85900. //impostor.physicsBody.dispose();
  85901. //Same as : (older oimo versions)
  85902. this.world.removeRigidBody(impostor.physicsBody);
  85903. };
  85904. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85905. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85906. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85907. if (!mainBody || !connectedBody) {
  85908. return;
  85909. }
  85910. var jointData = impostorJoint.joint.jointData;
  85911. var options = jointData.nativeParams || {};
  85912. var type;
  85913. var nativeJointData = {
  85914. body1: mainBody,
  85915. body2: connectedBody,
  85916. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  85917. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  85918. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  85919. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  85920. min: options.min,
  85921. max: options.max,
  85922. collision: options.collision || jointData.collision,
  85923. spring: options.spring,
  85924. //supporting older version of Oimo
  85925. world: this.world
  85926. };
  85927. switch (impostorJoint.joint.type) {
  85928. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85929. type = "jointBall";
  85930. break;
  85931. case BABYLON.PhysicsJoint.SpringJoint:
  85932. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  85933. var springData = jointData;
  85934. nativeJointData.min = springData.length || nativeJointData.min;
  85935. //Max should also be set, just make sure it is at least min
  85936. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  85937. case BABYLON.PhysicsJoint.DistanceJoint:
  85938. type = "jointDistance";
  85939. nativeJointData.max = jointData.maxDistance;
  85940. break;
  85941. case BABYLON.PhysicsJoint.PrismaticJoint:
  85942. type = "jointPrisme";
  85943. break;
  85944. case BABYLON.PhysicsJoint.SliderJoint:
  85945. type = "jointSlide";
  85946. break;
  85947. case BABYLON.PhysicsJoint.WheelJoint:
  85948. type = "jointWheel";
  85949. break;
  85950. case BABYLON.PhysicsJoint.HingeJoint:
  85951. default:
  85952. type = "jointHinge";
  85953. break;
  85954. }
  85955. nativeJointData.type = type;
  85956. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  85957. };
  85958. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85959. //Bug in Oimo prevents us from disposing a joint in the playground
  85960. //joint.joint.physicsJoint.dispose();
  85961. //So we will bruteforce it!
  85962. try {
  85963. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  85964. }
  85965. catch (e) {
  85966. BABYLON.Tools.Warn(e);
  85967. }
  85968. };
  85969. OimoJSPlugin.prototype.isSupported = function () {
  85970. return this.BJSOIMO !== undefined;
  85971. };
  85972. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  85973. if (!impostor.physicsBody.sleeping) {
  85974. //TODO check that
  85975. /*if (impostor.physicsBody.shapes.next) {
  85976. var parentShape = this._getLastShape(impostor.physicsBody);
  85977. impostor.object.position.copyFrom(parentShape.position);
  85978. console.log(parentShape.position);
  85979. } else {*/
  85980. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  85981. //}
  85982. if (impostor.object.rotationQuaternion) {
  85983. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  85984. }
  85985. }
  85986. };
  85987. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  85988. var body = impostor.physicsBody;
  85989. body.position.copy(newPosition);
  85990. body.orientation.copy(newRotation);
  85991. body.syncShapes();
  85992. body.awake();
  85993. };
  85994. /*private _getLastShape(body: any): any {
  85995. var lastShape = body.shapes;
  85996. while (lastShape.next) {
  85997. lastShape = lastShape.next;
  85998. }
  85999. return lastShape;
  86000. }*/
  86001. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86002. impostor.physicsBody.linearVelocity.copy(velocity);
  86003. };
  86004. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86005. impostor.physicsBody.angularVelocity.copy(velocity);
  86006. };
  86007. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86008. var v = impostor.physicsBody.linearVelocity;
  86009. if (!v) {
  86010. return null;
  86011. }
  86012. return new BABYLON.Vector3(v.x, v.y, v.z);
  86013. };
  86014. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86015. var v = impostor.physicsBody.angularVelocity;
  86016. if (!v) {
  86017. return null;
  86018. }
  86019. return new BABYLON.Vector3(v.x, v.y, v.z);
  86020. };
  86021. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86022. var staticBody = mass === 0;
  86023. //this will actually set the body's density and not its mass.
  86024. //But this is how oimo treats the mass variable.
  86025. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  86026. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  86027. };
  86028. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  86029. return impostor.physicsBody.shapes.density;
  86030. };
  86031. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  86032. return impostor.physicsBody.shapes.friction;
  86033. };
  86034. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86035. impostor.physicsBody.shapes.friction = friction;
  86036. };
  86037. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86038. return impostor.physicsBody.shapes.restitution;
  86039. };
  86040. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86041. impostor.physicsBody.shapes.restitution = restitution;
  86042. };
  86043. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  86044. impostor.physicsBody.sleep();
  86045. };
  86046. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  86047. impostor.physicsBody.awake();
  86048. };
  86049. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86050. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  86051. if (minDistance !== void 0) {
  86052. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  86053. }
  86054. };
  86055. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86056. //TODO separate rotational and transational motors.
  86057. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86058. if (motor) {
  86059. motor.setMotor(speed, maxForce);
  86060. }
  86061. };
  86062. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  86063. //TODO separate rotational and transational motors.
  86064. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86065. if (motor) {
  86066. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  86067. }
  86068. };
  86069. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86070. var body = impostor.physicsBody;
  86071. mesh.position.x = body.position.x;
  86072. mesh.position.y = body.position.y;
  86073. mesh.position.z = body.position.z;
  86074. if (mesh.rotationQuaternion) {
  86075. mesh.rotationQuaternion.x = body.orientation.x;
  86076. mesh.rotationQuaternion.y = body.orientation.y;
  86077. mesh.rotationQuaternion.z = body.orientation.z;
  86078. mesh.rotationQuaternion.w = body.orientation.s;
  86079. }
  86080. };
  86081. OimoJSPlugin.prototype.getRadius = function (impostor) {
  86082. return impostor.physicsBody.shapes.radius;
  86083. };
  86084. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86085. var shape = impostor.physicsBody.shapes;
  86086. result.x = shape.halfWidth * 2;
  86087. result.y = shape.halfHeight * 2;
  86088. result.z = shape.halfDepth * 2;
  86089. };
  86090. OimoJSPlugin.prototype.dispose = function () {
  86091. this.world.clear();
  86092. };
  86093. return OimoJSPlugin;
  86094. }());
  86095. BABYLON.OimoJSPlugin = OimoJSPlugin;
  86096. })(BABYLON || (BABYLON = {}));
  86097. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  86098. var BABYLON;
  86099. (function (BABYLON) {
  86100. /*
  86101. * Based on jsTGALoader - Javascript loader for TGA file
  86102. * By Vincent Thibault
  86103. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  86104. */
  86105. var TGATools = /** @class */ (function () {
  86106. function TGATools() {
  86107. }
  86108. TGATools.GetTGAHeader = function (data) {
  86109. var offset = 0;
  86110. var header = {
  86111. id_length: data[offset++],
  86112. colormap_type: data[offset++],
  86113. image_type: data[offset++],
  86114. colormap_index: data[offset++] | data[offset++] << 8,
  86115. colormap_length: data[offset++] | data[offset++] << 8,
  86116. colormap_size: data[offset++],
  86117. origin: [
  86118. data[offset++] | data[offset++] << 8,
  86119. data[offset++] | data[offset++] << 8
  86120. ],
  86121. width: data[offset++] | data[offset++] << 8,
  86122. height: data[offset++] | data[offset++] << 8,
  86123. pixel_size: data[offset++],
  86124. flags: data[offset++]
  86125. };
  86126. return header;
  86127. };
  86128. TGATools.UploadContent = function (gl, data) {
  86129. // Not enough data to contain header ?
  86130. if (data.length < 19) {
  86131. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  86132. return;
  86133. }
  86134. // Read Header
  86135. var offset = 18;
  86136. var header = TGATools.GetTGAHeader(data);
  86137. // Assume it's a valid Targa file.
  86138. if (header.id_length + offset > data.length) {
  86139. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  86140. return;
  86141. }
  86142. // Skip not needed data
  86143. offset += header.id_length;
  86144. var use_rle = false;
  86145. var use_pal = false;
  86146. var use_grey = false;
  86147. // Get some informations.
  86148. switch (header.image_type) {
  86149. case TGATools._TYPE_RLE_INDEXED:
  86150. use_rle = true;
  86151. case TGATools._TYPE_INDEXED:
  86152. use_pal = true;
  86153. break;
  86154. case TGATools._TYPE_RLE_RGB:
  86155. use_rle = true;
  86156. case TGATools._TYPE_RGB:
  86157. // use_rgb = true;
  86158. break;
  86159. case TGATools._TYPE_RLE_GREY:
  86160. use_rle = true;
  86161. case TGATools._TYPE_GREY:
  86162. use_grey = true;
  86163. break;
  86164. }
  86165. var pixel_data;
  86166. // var numAlphaBits = header.flags & 0xf;
  86167. var pixel_size = header.pixel_size >> 3;
  86168. var pixel_total = header.width * header.height * pixel_size;
  86169. // Read palettes
  86170. var palettes;
  86171. if (use_pal) {
  86172. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  86173. }
  86174. // Read LRE
  86175. if (use_rle) {
  86176. pixel_data = new Uint8Array(pixel_total);
  86177. var c, count, i;
  86178. var localOffset = 0;
  86179. var pixels = new Uint8Array(pixel_size);
  86180. while (offset < pixel_total && localOffset < pixel_total) {
  86181. c = data[offset++];
  86182. count = (c & 0x7f) + 1;
  86183. // RLE pixels
  86184. if (c & 0x80) {
  86185. // Bind pixel tmp array
  86186. for (i = 0; i < pixel_size; ++i) {
  86187. pixels[i] = data[offset++];
  86188. }
  86189. // Copy pixel array
  86190. for (i = 0; i < count; ++i) {
  86191. pixel_data.set(pixels, localOffset + i * pixel_size);
  86192. }
  86193. localOffset += pixel_size * count;
  86194. }
  86195. // Raw pixels
  86196. else {
  86197. count *= pixel_size;
  86198. for (i = 0; i < count; ++i) {
  86199. pixel_data[localOffset + i] = data[offset++];
  86200. }
  86201. localOffset += count;
  86202. }
  86203. }
  86204. }
  86205. // RAW Pixels
  86206. else {
  86207. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  86208. }
  86209. // Load to texture
  86210. var x_start, y_start, x_step, y_step, y_end, x_end;
  86211. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  86212. default:
  86213. case TGATools._ORIGIN_UL:
  86214. x_start = 0;
  86215. x_step = 1;
  86216. x_end = header.width;
  86217. y_start = 0;
  86218. y_step = 1;
  86219. y_end = header.height;
  86220. break;
  86221. case TGATools._ORIGIN_BL:
  86222. x_start = 0;
  86223. x_step = 1;
  86224. x_end = header.width;
  86225. y_start = header.height - 1;
  86226. y_step = -1;
  86227. y_end = -1;
  86228. break;
  86229. case TGATools._ORIGIN_UR:
  86230. x_start = header.width - 1;
  86231. x_step = -1;
  86232. x_end = -1;
  86233. y_start = 0;
  86234. y_step = 1;
  86235. y_end = header.height;
  86236. break;
  86237. case TGATools._ORIGIN_BR:
  86238. x_start = header.width - 1;
  86239. x_step = -1;
  86240. x_end = -1;
  86241. y_start = header.height - 1;
  86242. y_step = -1;
  86243. y_end = -1;
  86244. break;
  86245. }
  86246. // Load the specify method
  86247. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  86248. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  86249. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  86250. };
  86251. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86252. var image = pixel_data, colormap = palettes;
  86253. var width = header.width, height = header.height;
  86254. var color, i = 0, x, y;
  86255. var imageData = new Uint8Array(width * height * 4);
  86256. for (y = y_start; y !== y_end; y += y_step) {
  86257. for (x = x_start; x !== x_end; x += x_step, i++) {
  86258. color = image[i];
  86259. imageData[(x + width * y) * 4 + 3] = 255;
  86260. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  86261. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  86262. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  86263. }
  86264. }
  86265. return imageData;
  86266. };
  86267. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86268. var image = pixel_data;
  86269. var width = header.width, height = header.height;
  86270. var color, i = 0, x, y;
  86271. var imageData = new Uint8Array(width * height * 4);
  86272. for (y = y_start; y !== y_end; y += y_step) {
  86273. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86274. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  86275. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  86276. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  86277. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  86278. imageData[(x + width * y) * 4 + 0] = r;
  86279. imageData[(x + width * y) * 4 + 1] = g;
  86280. imageData[(x + width * y) * 4 + 2] = b;
  86281. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  86282. }
  86283. }
  86284. return imageData;
  86285. };
  86286. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86287. var image = pixel_data;
  86288. var width = header.width, height = header.height;
  86289. var i = 0, x, y;
  86290. var imageData = new Uint8Array(width * height * 4);
  86291. for (y = y_start; y !== y_end; y += y_step) {
  86292. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  86293. imageData[(x + width * y) * 4 + 3] = 255;
  86294. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86295. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86296. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86297. }
  86298. }
  86299. return imageData;
  86300. };
  86301. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86302. var image = pixel_data;
  86303. var width = header.width, height = header.height;
  86304. var i = 0, x, y;
  86305. var imageData = new Uint8Array(width * height * 4);
  86306. for (y = y_start; y !== y_end; y += y_step) {
  86307. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  86308. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86309. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86310. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86311. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  86312. }
  86313. }
  86314. return imageData;
  86315. };
  86316. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86317. var image = pixel_data;
  86318. var width = header.width, height = header.height;
  86319. var color, i = 0, x, y;
  86320. var imageData = new Uint8Array(width * height * 4);
  86321. for (y = y_start; y !== y_end; y += y_step) {
  86322. for (x = x_start; x !== x_end; x += x_step, i++) {
  86323. color = image[i];
  86324. imageData[(x + width * y) * 4 + 0] = color;
  86325. imageData[(x + width * y) * 4 + 1] = color;
  86326. imageData[(x + width * y) * 4 + 2] = color;
  86327. imageData[(x + width * y) * 4 + 3] = 255;
  86328. }
  86329. }
  86330. return imageData;
  86331. };
  86332. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86333. var image = pixel_data;
  86334. var width = header.width, height = header.height;
  86335. var i = 0, x, y;
  86336. var imageData = new Uint8Array(width * height * 4);
  86337. for (y = y_start; y !== y_end; y += y_step) {
  86338. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86339. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  86340. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  86341. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86342. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  86343. }
  86344. }
  86345. return imageData;
  86346. };
  86347. //private static _TYPE_NO_DATA = 0;
  86348. TGATools._TYPE_INDEXED = 1;
  86349. TGATools._TYPE_RGB = 2;
  86350. TGATools._TYPE_GREY = 3;
  86351. TGATools._TYPE_RLE_INDEXED = 9;
  86352. TGATools._TYPE_RLE_RGB = 10;
  86353. TGATools._TYPE_RLE_GREY = 11;
  86354. TGATools._ORIGIN_MASK = 0x30;
  86355. TGATools._ORIGIN_SHIFT = 0x04;
  86356. TGATools._ORIGIN_BL = 0x00;
  86357. TGATools._ORIGIN_BR = 0x01;
  86358. TGATools._ORIGIN_UL = 0x02;
  86359. TGATools._ORIGIN_UR = 0x03;
  86360. return TGATools;
  86361. }());
  86362. BABYLON.TGATools = TGATools;
  86363. })(BABYLON || (BABYLON = {}));
  86364. //# sourceMappingURL=babylon.tga.js.map
  86365. var BABYLON;
  86366. (function (BABYLON) {
  86367. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  86368. // All values and structures referenced from:
  86369. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  86370. var DDS_MAGIC = 0x20534444;
  86371. var
  86372. //DDSD_CAPS = 0x1,
  86373. //DDSD_HEIGHT = 0x2,
  86374. //DDSD_WIDTH = 0x4,
  86375. //DDSD_PITCH = 0x8,
  86376. //DDSD_PIXELFORMAT = 0x1000,
  86377. DDSD_MIPMAPCOUNT = 0x20000;
  86378. //DDSD_LINEARSIZE = 0x80000,
  86379. //DDSD_DEPTH = 0x800000;
  86380. // var DDSCAPS_COMPLEX = 0x8,
  86381. // DDSCAPS_MIPMAP = 0x400000,
  86382. // DDSCAPS_TEXTURE = 0x1000;
  86383. var DDSCAPS2_CUBEMAP = 0x200;
  86384. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  86385. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  86386. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  86387. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  86388. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  86389. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  86390. // DDSCAPS2_VOLUME = 0x200000;
  86391. var
  86392. //DDPF_ALPHAPIXELS = 0x1,
  86393. //DDPF_ALPHA = 0x2,
  86394. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  86395. //DDPF_YUV = 0x200,
  86396. DDPF_LUMINANCE = 0x20000;
  86397. function FourCCToInt32(value) {
  86398. return value.charCodeAt(0) +
  86399. (value.charCodeAt(1) << 8) +
  86400. (value.charCodeAt(2) << 16) +
  86401. (value.charCodeAt(3) << 24);
  86402. }
  86403. function Int32ToFourCC(value) {
  86404. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  86405. }
  86406. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  86407. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  86408. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  86409. var FOURCC_DX10 = FourCCToInt32("DX10");
  86410. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  86411. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  86412. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  86413. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  86414. var headerLengthInt = 31; // The header length in 32 bit ints
  86415. // Offsets into the header array
  86416. var off_magic = 0;
  86417. var off_size = 1;
  86418. var off_flags = 2;
  86419. var off_height = 3;
  86420. var off_width = 4;
  86421. var off_mipmapCount = 7;
  86422. var off_pfFlags = 20;
  86423. var off_pfFourCC = 21;
  86424. var off_RGBbpp = 22;
  86425. var off_RMask = 23;
  86426. var off_GMask = 24;
  86427. var off_BMask = 25;
  86428. var off_AMask = 26;
  86429. // var off_caps1 = 27;
  86430. var off_caps2 = 28;
  86431. // var off_caps3 = 29;
  86432. // var off_caps4 = 30;
  86433. var off_dxgiFormat = 32;
  86434. ;
  86435. var DDSTools = /** @class */ (function () {
  86436. function DDSTools() {
  86437. }
  86438. DDSTools.GetDDSInfo = function (arrayBuffer) {
  86439. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  86440. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  86441. var mipmapCount = 1;
  86442. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  86443. mipmapCount = Math.max(1, header[off_mipmapCount]);
  86444. }
  86445. var fourCC = header[off_pfFourCC];
  86446. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  86447. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86448. switch (fourCC) {
  86449. case FOURCC_D3DFMT_R16G16B16A16F:
  86450. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86451. break;
  86452. case FOURCC_D3DFMT_R32G32B32A32F:
  86453. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86454. break;
  86455. case FOURCC_DX10:
  86456. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  86457. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86458. break;
  86459. }
  86460. }
  86461. return {
  86462. width: header[off_width],
  86463. height: header[off_height],
  86464. mipmapCount: mipmapCount,
  86465. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  86466. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  86467. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  86468. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  86469. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  86470. dxgiFormat: dxgiFormat,
  86471. textureType: textureType
  86472. };
  86473. };
  86474. DDSTools._ToHalfFloat = function (value) {
  86475. if (!DDSTools._FloatView) {
  86476. DDSTools._FloatView = new Float32Array(1);
  86477. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  86478. }
  86479. DDSTools._FloatView[0] = value;
  86480. var x = DDSTools._Int32View[0];
  86481. var bits = (x >> 16) & 0x8000; /* Get the sign */
  86482. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  86483. var e = (x >> 23) & 0xff; /* Using int is faster here */
  86484. /* If zero, or denormal, or exponent underflows too much for a denormal
  86485. * half, return signed zero. */
  86486. if (e < 103) {
  86487. return bits;
  86488. }
  86489. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  86490. if (e > 142) {
  86491. bits |= 0x7c00;
  86492. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  86493. * not Inf, so make sure we set one mantissa bit too. */
  86494. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  86495. return bits;
  86496. }
  86497. /* If exponent underflows but not too much, return a denormal */
  86498. if (e < 113) {
  86499. m |= 0x0800;
  86500. /* Extra rounding may overflow and set mantissa to 0 and exponent
  86501. * to 1, which is OK. */
  86502. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  86503. return bits;
  86504. }
  86505. bits |= ((e - 112) << 10) | (m >> 1);
  86506. bits += m & 1;
  86507. return bits;
  86508. };
  86509. DDSTools._FromHalfFloat = function (value) {
  86510. var s = (value & 0x8000) >> 15;
  86511. var e = (value & 0x7C00) >> 10;
  86512. var f = value & 0x03FF;
  86513. if (e === 0) {
  86514. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  86515. }
  86516. else if (e == 0x1F) {
  86517. return f ? NaN : ((s ? -1 : 1) * Infinity);
  86518. }
  86519. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  86520. };
  86521. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86522. var destArray = new Float32Array(dataLength);
  86523. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86524. var index = 0;
  86525. for (var y = 0; y < height; y++) {
  86526. for (var x = 0; x < width; x++) {
  86527. var srcPos = (x + y * width) * 4;
  86528. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  86529. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  86530. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  86531. if (DDSTools.StoreLODInAlphaChannel) {
  86532. destArray[index + 3] = lod;
  86533. }
  86534. else {
  86535. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  86536. }
  86537. index += 4;
  86538. }
  86539. }
  86540. return destArray;
  86541. };
  86542. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86543. if (DDSTools.StoreLODInAlphaChannel) {
  86544. var destArray = new Uint16Array(dataLength);
  86545. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86546. var index = 0;
  86547. for (var y = 0; y < height; y++) {
  86548. for (var x = 0; x < width; x++) {
  86549. var srcPos = (x + y * width) * 4;
  86550. destArray[index] = srcData[srcPos];
  86551. destArray[index + 1] = srcData[srcPos + 1];
  86552. destArray[index + 2] = srcData[srcPos + 2];
  86553. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  86554. index += 4;
  86555. }
  86556. }
  86557. return destArray;
  86558. }
  86559. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  86560. };
  86561. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86562. if (DDSTools.StoreLODInAlphaChannel) {
  86563. var destArray = new Float32Array(dataLength);
  86564. var srcData = new Float32Array(arrayBuffer, dataOffset);
  86565. var index = 0;
  86566. for (var y = 0; y < height; y++) {
  86567. for (var x = 0; x < width; x++) {
  86568. var srcPos = (x + y * width) * 4;
  86569. destArray[index] = srcData[srcPos];
  86570. destArray[index + 1] = srcData[srcPos + 1];
  86571. destArray[index + 2] = srcData[srcPos + 2];
  86572. destArray[index + 3] = lod;
  86573. index += 4;
  86574. }
  86575. }
  86576. return destArray;
  86577. }
  86578. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  86579. };
  86580. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86581. var destArray = new Uint8Array(dataLength);
  86582. var srcData = new Float32Array(arrayBuffer, dataOffset);
  86583. var index = 0;
  86584. for (var y = 0; y < height; y++) {
  86585. for (var x = 0; x < width; x++) {
  86586. var srcPos = (x + y * width) * 4;
  86587. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  86588. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  86589. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  86590. if (DDSTools.StoreLODInAlphaChannel) {
  86591. destArray[index + 3] = lod;
  86592. }
  86593. else {
  86594. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  86595. }
  86596. index += 4;
  86597. }
  86598. }
  86599. return destArray;
  86600. };
  86601. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86602. var destArray = new Uint8Array(dataLength);
  86603. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86604. var index = 0;
  86605. for (var y = 0; y < height; y++) {
  86606. for (var x = 0; x < width; x++) {
  86607. var srcPos = (x + y * width) * 4;
  86608. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  86609. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  86610. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  86611. if (DDSTools.StoreLODInAlphaChannel) {
  86612. destArray[index + 3] = lod;
  86613. }
  86614. else {
  86615. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  86616. }
  86617. index += 4;
  86618. }
  86619. }
  86620. return destArray;
  86621. };
  86622. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  86623. var byteArray = new Uint8Array(dataLength);
  86624. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86625. var index = 0;
  86626. for (var y = 0; y < height; y++) {
  86627. for (var x = 0; x < width; x++) {
  86628. var srcPos = (x + y * width) * 4;
  86629. byteArray[index] = srcData[srcPos + rOffset];
  86630. byteArray[index + 1] = srcData[srcPos + gOffset];
  86631. byteArray[index + 2] = srcData[srcPos + bOffset];
  86632. byteArray[index + 3] = srcData[srcPos + aOffset];
  86633. index += 4;
  86634. }
  86635. }
  86636. return byteArray;
  86637. };
  86638. DDSTools._ExtractLongWordOrder = function (value) {
  86639. if (value === 0 || value === 255 || value === -16777216) {
  86640. return 0;
  86641. }
  86642. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  86643. };
  86644. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  86645. var byteArray = new Uint8Array(dataLength);
  86646. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86647. var index = 0;
  86648. for (var y = 0; y < height; y++) {
  86649. for (var x = 0; x < width; x++) {
  86650. var srcPos = (x + y * width) * 3;
  86651. byteArray[index] = srcData[srcPos + rOffset];
  86652. byteArray[index + 1] = srcData[srcPos + gOffset];
  86653. byteArray[index + 2] = srcData[srcPos + bOffset];
  86654. index += 3;
  86655. }
  86656. }
  86657. return byteArray;
  86658. };
  86659. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  86660. var byteArray = new Uint8Array(dataLength);
  86661. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86662. var index = 0;
  86663. for (var y = 0; y < height; y++) {
  86664. for (var x = 0; x < width; x++) {
  86665. var srcPos = (x + y * width);
  86666. byteArray[index] = srcData[srcPos];
  86667. index++;
  86668. }
  86669. }
  86670. return byteArray;
  86671. };
  86672. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  86673. if (lodIndex === void 0) { lodIndex = -1; }
  86674. var sphericalPolynomialFaces = null;
  86675. if (info.sphericalPolynomial) {
  86676. sphericalPolynomialFaces = new Array();
  86677. }
  86678. var ext = engine.getCaps().s3tc;
  86679. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  86680. var fourCC, width, height, dataLength = 0, dataOffset;
  86681. var byteArray, mipmapCount, mip;
  86682. var internalFormat = 0;
  86683. var format = 0;
  86684. var blockBytes = 1;
  86685. if (header[off_magic] !== DDS_MAGIC) {
  86686. BABYLON.Tools.Error("Invalid magic number in DDS header");
  86687. return;
  86688. }
  86689. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  86690. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  86691. return;
  86692. }
  86693. if (info.isCompressed && !ext) {
  86694. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  86695. return;
  86696. }
  86697. var bpp = header[off_RGBbpp];
  86698. dataOffset = header[off_size] + 4;
  86699. var computeFormats = false;
  86700. if (info.isFourCC) {
  86701. fourCC = header[off_pfFourCC];
  86702. switch (fourCC) {
  86703. case FOURCC_DXT1:
  86704. blockBytes = 8;
  86705. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  86706. break;
  86707. case FOURCC_DXT3:
  86708. blockBytes = 16;
  86709. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  86710. break;
  86711. case FOURCC_DXT5:
  86712. blockBytes = 16;
  86713. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  86714. break;
  86715. case FOURCC_D3DFMT_R16G16B16A16F:
  86716. computeFormats = true;
  86717. break;
  86718. case FOURCC_D3DFMT_R32G32B32A32F:
  86719. computeFormats = true;
  86720. break;
  86721. case FOURCC_DX10:
  86722. // There is an additionnal header so dataOffset need to be changed
  86723. dataOffset += 5 * 4; // 5 uints
  86724. var supported = false;
  86725. switch (info.dxgiFormat) {
  86726. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  86727. computeFormats = true;
  86728. supported = true;
  86729. break;
  86730. case DXGI_FORMAT_B8G8R8X8_UNORM:
  86731. info.isRGB = true;
  86732. info.isFourCC = false;
  86733. bpp = 32;
  86734. supported = true;
  86735. break;
  86736. }
  86737. if (supported) {
  86738. break;
  86739. }
  86740. default:
  86741. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  86742. return;
  86743. }
  86744. }
  86745. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  86746. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  86747. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  86748. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  86749. if (computeFormats) {
  86750. format = engine._getWebGLTextureType(info.textureType);
  86751. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86752. }
  86753. mipmapCount = 1;
  86754. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  86755. mipmapCount = Math.max(1, header[off_mipmapCount]);
  86756. }
  86757. for (var face = 0; face < faces; face++) {
  86758. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  86759. width = header[off_width];
  86760. height = header[off_height];
  86761. for (mip = 0; mip < mipmapCount; ++mip) {
  86762. if (lodIndex === -1 || lodIndex === mip) {
  86763. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  86764. var i = (lodIndex === -1) ? mip : 0;
  86765. if (!info.isCompressed && info.isFourCC) {
  86766. dataLength = width * height * 4;
  86767. var floatArray = null;
  86768. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  86769. if (bpp === 128) {
  86770. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86771. if (sphericalPolynomialFaces && i == 0) {
  86772. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86773. }
  86774. }
  86775. else if (bpp === 64) {
  86776. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86777. if (sphericalPolynomialFaces && i == 0) {
  86778. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86779. }
  86780. }
  86781. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86782. format = engine._getWebGLTextureType(info.textureType);
  86783. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86784. }
  86785. else {
  86786. if (bpp === 128) {
  86787. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86788. if (sphericalPolynomialFaces && i == 0) {
  86789. sphericalPolynomialFaces.push(floatArray);
  86790. }
  86791. }
  86792. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  86793. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86794. if (sphericalPolynomialFaces && i == 0) {
  86795. sphericalPolynomialFaces.push(floatArray);
  86796. }
  86797. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86798. format = engine._getWebGLTextureType(info.textureType);
  86799. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86800. }
  86801. else { // 64
  86802. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86803. if (sphericalPolynomialFaces && i == 0) {
  86804. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86805. }
  86806. }
  86807. }
  86808. if (floatArray) {
  86809. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  86810. }
  86811. }
  86812. else if (info.isRGB) {
  86813. if (bpp === 24) {
  86814. dataLength = width * height * 3;
  86815. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  86816. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  86817. }
  86818. else { // 32
  86819. dataLength = width * height * 4;
  86820. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  86821. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  86822. }
  86823. }
  86824. else if (info.isLuminance) {
  86825. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  86826. var unpaddedRowSize = width;
  86827. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  86828. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  86829. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  86830. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  86831. }
  86832. else {
  86833. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  86834. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  86835. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  86836. }
  86837. }
  86838. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  86839. width *= 0.5;
  86840. height *= 0.5;
  86841. width = Math.max(1.0, width);
  86842. height = Math.max(1.0, height);
  86843. }
  86844. if (currentFace !== undefined) {
  86845. // Loading a single face
  86846. break;
  86847. }
  86848. }
  86849. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  86850. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  86851. size: header[off_width],
  86852. right: sphericalPolynomialFaces[0],
  86853. left: sphericalPolynomialFaces[1],
  86854. up: sphericalPolynomialFaces[2],
  86855. down: sphericalPolynomialFaces[3],
  86856. front: sphericalPolynomialFaces[4],
  86857. back: sphericalPolynomialFaces[5],
  86858. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  86859. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  86860. gammaSpace: false,
  86861. });
  86862. }
  86863. else {
  86864. info.sphericalPolynomial = undefined;
  86865. }
  86866. };
  86867. DDSTools.StoreLODInAlphaChannel = false;
  86868. return DDSTools;
  86869. }());
  86870. BABYLON.DDSTools = DDSTools;
  86871. })(BABYLON || (BABYLON = {}));
  86872. //# sourceMappingURL=babylon.dds.js.map
  86873. var BABYLON;
  86874. (function (BABYLON) {
  86875. /**
  86876. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  86877. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  86878. */
  86879. var KhronosTextureContainer = /** @class */ (function () {
  86880. /**
  86881. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  86882. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  86883. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  86884. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  86885. */
  86886. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  86887. this.arrayBuffer = arrayBuffer;
  86888. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  86889. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  86890. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  86891. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  86892. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  86893. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  86894. BABYLON.Tools.Error("texture missing KTX identifier");
  86895. return;
  86896. }
  86897. // load the reset of the header in native 32 bit int
  86898. var header = new Int32Array(this.arrayBuffer, 12, 13);
  86899. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  86900. var oppositeEndianess = header[0] === 0x01020304;
  86901. // read all the header elements in order they exist in the file, without modification (sans endainness)
  86902. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  86903. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  86904. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  86905. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  86906. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  86907. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  86908. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  86909. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  86910. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  86911. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  86912. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  86913. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  86914. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  86915. if (this.glType !== 0) {
  86916. BABYLON.Tools.Error("only compressed formats currently supported");
  86917. return;
  86918. }
  86919. else {
  86920. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  86921. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  86922. }
  86923. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  86924. BABYLON.Tools.Error("only 2D textures currently supported");
  86925. return;
  86926. }
  86927. if (this.numberOfArrayElements !== 0) {
  86928. BABYLON.Tools.Error("texture arrays not currently supported");
  86929. return;
  86930. }
  86931. if (this.numberOfFaces !== facesExpected) {
  86932. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  86933. return;
  86934. }
  86935. // we now have a completely validated file, so could use existence of loadType as success
  86936. // would need to make this more elaborate & adjust checks above to support more than one load type
  86937. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  86938. }
  86939. // not as fast hardware based, but will probably never need to use
  86940. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  86941. return ((val & 0xFF) << 24)
  86942. | ((val & 0xFF00) << 8)
  86943. | ((val >> 8) & 0xFF00)
  86944. | ((val >> 24) & 0xFF);
  86945. };
  86946. /**
  86947. * It is assumed that the texture has already been created & is currently bound
  86948. */
  86949. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  86950. switch (this.loadType) {
  86951. case KhronosTextureContainer.COMPRESSED_2D:
  86952. this._upload2DCompressedLevels(gl, loadMipmaps);
  86953. break;
  86954. case KhronosTextureContainer.TEX_2D:
  86955. case KhronosTextureContainer.COMPRESSED_3D:
  86956. case KhronosTextureContainer.TEX_3D:
  86957. }
  86958. };
  86959. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  86960. // initialize width & height for level 1
  86961. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  86962. var width = this.pixelWidth;
  86963. var height = this.pixelHeight;
  86964. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  86965. for (var level = 0; level < mipmapCount; level++) {
  86966. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  86967. for (var face = 0; face < this.numberOfFaces; face++) {
  86968. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  86969. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  86970. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  86971. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  86972. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  86973. }
  86974. width = Math.max(1.0, width * 0.5);
  86975. height = Math.max(1.0, height * 0.5);
  86976. }
  86977. };
  86978. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  86979. // load types
  86980. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  86981. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  86982. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  86983. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  86984. return KhronosTextureContainer;
  86985. }());
  86986. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  86987. })(BABYLON || (BABYLON = {}));
  86988. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  86989. var BABYLON;
  86990. (function (BABYLON) {
  86991. var Debug;
  86992. (function (Debug) {
  86993. /**
  86994. * Class used to render a debug view of a given skeleton
  86995. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  86996. */
  86997. var SkeletonViewer = /** @class */ (function () {
  86998. /**
  86999. * Creates a new SkeletonViewer
  87000. * @param skeleton defines the skeleton to render
  87001. * @param mesh defines the mesh attached to the skeleton
  87002. * @param scene defines the hosting scene
  87003. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  87004. * @param renderingGroupId defines the rendering group id to use with the viewer
  87005. */
  87006. function SkeletonViewer(
  87007. /** defines the skeleton to render */
  87008. skeleton,
  87009. /** defines the mesh attached to the skeleton */
  87010. mesh, scene,
  87011. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  87012. autoUpdateBonesMatrices,
  87013. /** defines the rendering group id to use with the viewer */
  87014. renderingGroupId) {
  87015. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  87016. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  87017. this.skeleton = skeleton;
  87018. this.mesh = mesh;
  87019. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  87020. this.renderingGroupId = renderingGroupId;
  87021. /** Gets or sets the color used to render the skeleton */
  87022. this.color = BABYLON.Color3.White();
  87023. this._debugLines = new Array();
  87024. this._isEnabled = false;
  87025. this._scene = scene;
  87026. this.update();
  87027. this._renderFunction = this.update.bind(this);
  87028. }
  87029. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  87030. get: function () {
  87031. return this._isEnabled;
  87032. },
  87033. /** Gets or sets a boolean indicating if the viewer is enabled */
  87034. set: function (value) {
  87035. if (this._isEnabled === value) {
  87036. return;
  87037. }
  87038. this._isEnabled = value;
  87039. if (value) {
  87040. this._scene.registerBeforeRender(this._renderFunction);
  87041. }
  87042. else {
  87043. this._scene.unregisterBeforeRender(this._renderFunction);
  87044. }
  87045. },
  87046. enumerable: true,
  87047. configurable: true
  87048. });
  87049. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  87050. if (x === void 0) { x = 0; }
  87051. if (y === void 0) { y = 0; }
  87052. if (z === void 0) { z = 0; }
  87053. var tmat = BABYLON.Tmp.Matrix[0];
  87054. var parentBone = bone.getParent();
  87055. tmat.copyFrom(bone.getLocalMatrix());
  87056. if (x !== 0 || y !== 0 || z !== 0) {
  87057. var tmat2 = BABYLON.Tmp.Matrix[1];
  87058. BABYLON.Matrix.IdentityToRef(tmat2);
  87059. tmat2.m[12] = x;
  87060. tmat2.m[13] = y;
  87061. tmat2.m[14] = z;
  87062. tmat2.multiplyToRef(tmat, tmat);
  87063. }
  87064. if (parentBone) {
  87065. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  87066. }
  87067. tmat.multiplyToRef(meshMat, tmat);
  87068. position.x = tmat.m[12];
  87069. position.y = tmat.m[13];
  87070. position.z = tmat.m[14];
  87071. };
  87072. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  87073. var len = bones.length;
  87074. var meshPos = this.mesh.position;
  87075. for (var i = 0; i < len; i++) {
  87076. var bone = bones[i];
  87077. var points = this._debugLines[i];
  87078. if (!points) {
  87079. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87080. this._debugLines[i] = points;
  87081. }
  87082. this._getBonePosition(points[0], bone, meshMat);
  87083. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  87084. points[0].subtractInPlace(meshPos);
  87085. points[1].subtractInPlace(meshPos);
  87086. }
  87087. };
  87088. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  87089. var len = bones.length;
  87090. var boneNum = 0;
  87091. var meshPos = this.mesh.position;
  87092. for (var i = len - 1; i >= 0; i--) {
  87093. var childBone = bones[i];
  87094. var parentBone = childBone.getParent();
  87095. if (!parentBone) {
  87096. continue;
  87097. }
  87098. var points = this._debugLines[boneNum];
  87099. if (!points) {
  87100. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87101. this._debugLines[boneNum] = points;
  87102. }
  87103. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  87104. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  87105. points[0].subtractInPlace(meshPos);
  87106. points[1].subtractInPlace(meshPos);
  87107. boneNum++;
  87108. }
  87109. };
  87110. /** Update the viewer to sync with current skeleton state */
  87111. SkeletonViewer.prototype.update = function () {
  87112. if (this.autoUpdateBonesMatrices) {
  87113. this.skeleton.computeAbsoluteTransforms();
  87114. }
  87115. if (this.skeleton.bones[0].length === undefined) {
  87116. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87117. }
  87118. else {
  87119. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87120. }
  87121. if (!this._debugMesh) {
  87122. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  87123. this._debugMesh.renderingGroupId = this.renderingGroupId;
  87124. }
  87125. else {
  87126. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  87127. }
  87128. this._debugMesh.position.copyFrom(this.mesh.position);
  87129. this._debugMesh.color = this.color;
  87130. };
  87131. /** Release associated resources */
  87132. SkeletonViewer.prototype.dispose = function () {
  87133. if (this._debugMesh) {
  87134. this.isEnabled = false;
  87135. this._debugMesh.dispose();
  87136. this._debugMesh = null;
  87137. }
  87138. };
  87139. return SkeletonViewer;
  87140. }());
  87141. Debug.SkeletonViewer = SkeletonViewer;
  87142. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87143. })(BABYLON || (BABYLON = {}));
  87144. //# sourceMappingURL=babylon.skeletonViewer.js.map
  87145. /**
  87146. * Module Debug contains the (visual) components to debug a scene correctly
  87147. */
  87148. var BABYLON;
  87149. (function (BABYLON) {
  87150. var Debug;
  87151. (function (Debug) {
  87152. /**
  87153. * The Axes viewer will show 3 axes in a specific point in space
  87154. */
  87155. var AxesViewer = /** @class */ (function () {
  87156. /**
  87157. * Creates a new AxesViewer
  87158. * @param scene defines the hosting scene
  87159. * @param scaleLines defines a number used to scale line length (1 by default)
  87160. */
  87161. function AxesViewer(scene, scaleLines) {
  87162. if (scaleLines === void 0) { scaleLines = 1; }
  87163. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87164. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87165. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87166. /**
  87167. * Gets or sets a number used to scale line length
  87168. */
  87169. this.scaleLines = 1;
  87170. this.scaleLines = scaleLines;
  87171. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  87172. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  87173. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  87174. this._xmesh.renderingGroupId = 2;
  87175. this._ymesh.renderingGroupId = 2;
  87176. this._zmesh.renderingGroupId = 2;
  87177. this._xmesh.material.checkReadyOnlyOnce = true;
  87178. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  87179. this._ymesh.material.checkReadyOnlyOnce = true;
  87180. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  87181. this._zmesh.material.checkReadyOnlyOnce = true;
  87182. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  87183. this.scene = scene;
  87184. }
  87185. /**
  87186. * Force the viewer to update
  87187. * @param position defines the position of the viewer
  87188. * @param xaxis defines the x axis of the viewer
  87189. * @param yaxis defines the y axis of the viewer
  87190. * @param zaxis defines the z axis of the viewer
  87191. */
  87192. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  87193. var scaleLines = this.scaleLines;
  87194. if (this._xmesh) {
  87195. this._xmesh.position.copyFrom(position);
  87196. }
  87197. if (this._ymesh) {
  87198. this._ymesh.position.copyFrom(position);
  87199. }
  87200. if (this._zmesh) {
  87201. this._zmesh.position.copyFrom(position);
  87202. }
  87203. var point2 = this._xline[1];
  87204. point2.x = xaxis.x * scaleLines;
  87205. point2.y = xaxis.y * scaleLines;
  87206. point2.z = xaxis.z * scaleLines;
  87207. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  87208. point2 = this._yline[1];
  87209. point2.x = yaxis.x * scaleLines;
  87210. point2.y = yaxis.y * scaleLines;
  87211. point2.z = yaxis.z * scaleLines;
  87212. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  87213. point2 = this._zline[1];
  87214. point2.x = zaxis.x * scaleLines;
  87215. point2.y = zaxis.y * scaleLines;
  87216. point2.z = zaxis.z * scaleLines;
  87217. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  87218. };
  87219. /** Releases resources */
  87220. AxesViewer.prototype.dispose = function () {
  87221. if (this._xmesh) {
  87222. this._xmesh.dispose();
  87223. }
  87224. if (this._ymesh) {
  87225. this._ymesh.dispose();
  87226. }
  87227. if (this._zmesh) {
  87228. this._zmesh.dispose();
  87229. }
  87230. this._xmesh = null;
  87231. this._ymesh = null;
  87232. this._zmesh = null;
  87233. this.scene = null;
  87234. };
  87235. return AxesViewer;
  87236. }());
  87237. Debug.AxesViewer = AxesViewer;
  87238. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87239. })(BABYLON || (BABYLON = {}));
  87240. //# sourceMappingURL=babylon.axesViewer.js.map
  87241. var BABYLON;
  87242. (function (BABYLON) {
  87243. var Debug;
  87244. (function (Debug) {
  87245. /**
  87246. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  87247. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  87248. */
  87249. var BoneAxesViewer = /** @class */ (function (_super) {
  87250. __extends(BoneAxesViewer, _super);
  87251. /**
  87252. * Creates a new BoneAxesViewer
  87253. * @param scene defines the hosting scene
  87254. * @param bone defines the target bone
  87255. * @param mesh defines the target mesh
  87256. * @param scaleLines defines a scaling factor for line length (1 by default)
  87257. */
  87258. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  87259. if (scaleLines === void 0) { scaleLines = 1; }
  87260. var _this = _super.call(this, scene, scaleLines) || this;
  87261. /** Gets current position */
  87262. _this.pos = BABYLON.Vector3.Zero();
  87263. /** Gets direction of X axis */
  87264. _this.xaxis = BABYLON.Vector3.Zero();
  87265. /** Gets direction of Y axis */
  87266. _this.yaxis = BABYLON.Vector3.Zero();
  87267. /** Gets direction of Z axis */
  87268. _this.zaxis = BABYLON.Vector3.Zero();
  87269. _this.mesh = mesh;
  87270. _this.bone = bone;
  87271. return _this;
  87272. }
  87273. /**
  87274. * Force the viewer to update
  87275. */
  87276. BoneAxesViewer.prototype.update = function () {
  87277. if (!this.mesh || !this.bone) {
  87278. return;
  87279. }
  87280. var bone = this.bone;
  87281. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  87282. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  87283. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  87284. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  87285. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  87286. };
  87287. /** Releases resources */
  87288. BoneAxesViewer.prototype.dispose = function () {
  87289. if (this.mesh) {
  87290. this.mesh = null;
  87291. this.bone = null;
  87292. _super.prototype.dispose.call(this);
  87293. }
  87294. };
  87295. return BoneAxesViewer;
  87296. }(Debug.AxesViewer));
  87297. Debug.BoneAxesViewer = BoneAxesViewer;
  87298. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87299. })(BABYLON || (BABYLON = {}));
  87300. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  87301. var BABYLON;
  87302. (function (BABYLON) {
  87303. var RayHelper = /** @class */ (function () {
  87304. function RayHelper(ray) {
  87305. this.ray = ray;
  87306. }
  87307. RayHelper.CreateAndShow = function (ray, scene, color) {
  87308. var helper = new RayHelper(ray);
  87309. helper.show(scene, color);
  87310. return helper;
  87311. };
  87312. RayHelper.prototype.show = function (scene, color) {
  87313. if (!this._renderFunction && this.ray) {
  87314. var ray = this.ray;
  87315. this._renderFunction = this._render.bind(this);
  87316. this._scene = scene;
  87317. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  87318. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  87319. if (this._renderFunction) {
  87320. this._scene.registerBeforeRender(this._renderFunction);
  87321. }
  87322. }
  87323. if (color && this._renderLine) {
  87324. this._renderLine.color.copyFrom(color);
  87325. }
  87326. };
  87327. RayHelper.prototype.hide = function () {
  87328. if (this._renderFunction && this._scene) {
  87329. this._scene.unregisterBeforeRender(this._renderFunction);
  87330. this._scene = null;
  87331. this._renderFunction = null;
  87332. if (this._renderLine) {
  87333. this._renderLine.dispose();
  87334. this._renderLine = null;
  87335. }
  87336. this._renderPoints = [];
  87337. }
  87338. };
  87339. RayHelper.prototype._render = function () {
  87340. var ray = this.ray;
  87341. if (!ray) {
  87342. return;
  87343. }
  87344. var point = this._renderPoints[1];
  87345. var len = Math.min(ray.length, 1000000);
  87346. point.copyFrom(ray.direction);
  87347. point.scaleInPlace(len);
  87348. point.addInPlace(ray.origin);
  87349. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  87350. };
  87351. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  87352. this._attachedToMesh = mesh;
  87353. var ray = this.ray;
  87354. if (!ray) {
  87355. return;
  87356. }
  87357. if (!ray.direction) {
  87358. ray.direction = BABYLON.Vector3.Zero();
  87359. }
  87360. if (!ray.origin) {
  87361. ray.origin = BABYLON.Vector3.Zero();
  87362. }
  87363. if (length) {
  87364. ray.length = length;
  87365. }
  87366. if (!meshSpaceOrigin) {
  87367. meshSpaceOrigin = BABYLON.Vector3.Zero();
  87368. }
  87369. if (!meshSpaceDirection) {
  87370. // -1 so that this will work with Mesh.lookAt
  87371. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  87372. }
  87373. if (!this._meshSpaceDirection) {
  87374. this._meshSpaceDirection = meshSpaceDirection.clone();
  87375. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  87376. }
  87377. else {
  87378. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  87379. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  87380. }
  87381. if (!this._updateToMeshFunction) {
  87382. this._updateToMeshFunction = this._updateToMesh.bind(this);
  87383. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  87384. }
  87385. this._updateToMesh();
  87386. };
  87387. RayHelper.prototype.detachFromMesh = function () {
  87388. if (this._attachedToMesh) {
  87389. if (this._updateToMeshFunction) {
  87390. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  87391. }
  87392. this._attachedToMesh = null;
  87393. this._updateToMeshFunction = null;
  87394. }
  87395. };
  87396. RayHelper.prototype._updateToMesh = function () {
  87397. var ray = this.ray;
  87398. if (!this._attachedToMesh || !ray) {
  87399. return;
  87400. }
  87401. if (this._attachedToMesh._isDisposed) {
  87402. this.detachFromMesh();
  87403. return;
  87404. }
  87405. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  87406. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  87407. };
  87408. RayHelper.prototype.dispose = function () {
  87409. this.hide();
  87410. this.detachFromMesh();
  87411. this.ray = null;
  87412. };
  87413. return RayHelper;
  87414. }());
  87415. BABYLON.RayHelper = RayHelper;
  87416. })(BABYLON || (BABYLON = {}));
  87417. //# sourceMappingURL=babylon.rayHelper.js.map
  87418. var BABYLON;
  87419. (function (BABYLON) {
  87420. // load the inspector using require, if not present in the global namespace.
  87421. var DebugLayer = /** @class */ (function () {
  87422. function DebugLayer(scene) {
  87423. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  87424. this._scene = scene;
  87425. // load inspector using require, if it doesn't exist on the global namespace.
  87426. }
  87427. /** Creates the inspector window. */
  87428. DebugLayer.prototype._createInspector = function (config) {
  87429. if (config === void 0) { config = {}; }
  87430. var popup = config.popup || false;
  87431. var initialTab = config.initialTab || 0;
  87432. var parentElement = config.parentElement || null;
  87433. if (!this._inspector) {
  87434. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  87435. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  87436. } // else nothing to do,; instance is already existing
  87437. };
  87438. DebugLayer.prototype.isVisible = function () {
  87439. if (!this._inspector) {
  87440. return false;
  87441. }
  87442. return true;
  87443. };
  87444. DebugLayer.prototype.hide = function () {
  87445. if (this._inspector) {
  87446. try {
  87447. this._inspector.dispose();
  87448. }
  87449. catch (e) {
  87450. // If the inspector has been removed directly from the inspector tool
  87451. }
  87452. this.onPropertyChangedObservable.clear();
  87453. this._inspector = null;
  87454. }
  87455. };
  87456. /**
  87457. *
  87458. * Launch the debugLayer.
  87459. *
  87460. * initialTab:
  87461. * | Value | Tab Name |
  87462. * | --- | --- |
  87463. * | 0 | Scene |
  87464. * | 1 | Console |
  87465. * | 2 | Stats |
  87466. * | 3 | Textures |
  87467. * | 4 | Mesh |
  87468. * | 5 | Light |
  87469. * | 6 | Material |
  87470. * | 7 | GLTF |
  87471. * | 8 | GUI |
  87472. * | 9 | Physics |
  87473. * | 10 | Camera |
  87474. * | 11 | Audio |
  87475. *
  87476. */
  87477. DebugLayer.prototype.show = function (config) {
  87478. if (config === void 0) { config = {}; }
  87479. if (typeof this.BJSINSPECTOR == 'undefined') {
  87480. // Load inspector and add it to the DOM
  87481. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  87482. }
  87483. else {
  87484. // Otherwise creates the inspector
  87485. this._createInspector(config);
  87486. this.onPropertyChangedObservable = new BABYLON.Observable();
  87487. }
  87488. };
  87489. /**
  87490. * Gets the active tab
  87491. * @return the index of the active tab or -1 if the inspector is hidden
  87492. */
  87493. DebugLayer.prototype.getActiveTab = function () {
  87494. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  87495. };
  87496. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  87497. return DebugLayer;
  87498. }());
  87499. BABYLON.DebugLayer = DebugLayer;
  87500. })(BABYLON || (BABYLON = {}));
  87501. //# sourceMappingURL=babylon.debugLayer.js.map
  87502. var BABYLON;
  87503. (function (BABYLON) {
  87504. var Debug;
  87505. (function (Debug) {
  87506. /**
  87507. * Used to show the physics impostor around the specific mesh
  87508. */
  87509. var PhysicsViewer = /** @class */ (function () {
  87510. /**
  87511. * Creates a new PhysicsViewer
  87512. * @param scene defines the hosting scene
  87513. */
  87514. function PhysicsViewer(scene) {
  87515. /** @hidden */
  87516. this._impostors = [];
  87517. /** @hidden */
  87518. this._meshes = [];
  87519. /** @hidden */
  87520. this._numMeshes = 0;
  87521. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87522. var physicEngine = this._scene.getPhysicsEngine();
  87523. if (physicEngine) {
  87524. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  87525. }
  87526. }
  87527. /** @hidden */
  87528. PhysicsViewer.prototype._updateDebugMeshes = function () {
  87529. var plugin = this._physicsEnginePlugin;
  87530. for (var i = 0; i < this._numMeshes; i++) {
  87531. var impostor = this._impostors[i];
  87532. if (!impostor) {
  87533. continue;
  87534. }
  87535. if (impostor.isDisposed) {
  87536. this.hideImpostor(this._impostors[i--]);
  87537. }
  87538. else {
  87539. var mesh = this._meshes[i];
  87540. if (mesh && plugin) {
  87541. plugin.syncMeshWithImpostor(mesh, impostor);
  87542. }
  87543. }
  87544. }
  87545. };
  87546. /**
  87547. * Renders a specified physic impostor
  87548. * @param impostor defines the impostor to render
  87549. */
  87550. PhysicsViewer.prototype.showImpostor = function (impostor) {
  87551. if (!this._scene) {
  87552. return;
  87553. }
  87554. for (var i = 0; i < this._numMeshes; i++) {
  87555. if (this._impostors[i] == impostor) {
  87556. return;
  87557. }
  87558. }
  87559. var debugMesh = this._getDebugMesh(impostor, this._scene);
  87560. if (debugMesh) {
  87561. this._impostors[this._numMeshes] = impostor;
  87562. this._meshes[this._numMeshes] = debugMesh;
  87563. if (this._numMeshes === 0) {
  87564. this._renderFunction = this._updateDebugMeshes.bind(this);
  87565. this._scene.registerBeforeRender(this._renderFunction);
  87566. }
  87567. this._numMeshes++;
  87568. }
  87569. };
  87570. /**
  87571. * Hides a specified physic impostor
  87572. * @param impostor defines the impostor to hide
  87573. */
  87574. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  87575. if (!impostor || !this._scene) {
  87576. return;
  87577. }
  87578. var removed = false;
  87579. for (var i = 0; i < this._numMeshes; i++) {
  87580. if (this._impostors[i] == impostor) {
  87581. var mesh = this._meshes[i];
  87582. if (!mesh) {
  87583. continue;
  87584. }
  87585. this._scene.removeMesh(mesh);
  87586. mesh.dispose();
  87587. this._numMeshes--;
  87588. if (this._numMeshes > 0) {
  87589. this._meshes[i] = this._meshes[this._numMeshes];
  87590. this._impostors[i] = this._impostors[this._numMeshes];
  87591. this._meshes[this._numMeshes] = null;
  87592. this._impostors[this._numMeshes] = null;
  87593. }
  87594. else {
  87595. this._meshes[0] = null;
  87596. this._impostors[0] = null;
  87597. }
  87598. removed = true;
  87599. break;
  87600. }
  87601. }
  87602. if (removed && this._numMeshes === 0) {
  87603. this._scene.unregisterBeforeRender(this._renderFunction);
  87604. }
  87605. };
  87606. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  87607. if (!this._debugMaterial) {
  87608. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  87609. this._debugMaterial.wireframe = true;
  87610. }
  87611. return this._debugMaterial;
  87612. };
  87613. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  87614. if (!this._debugBoxMesh) {
  87615. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  87616. this._debugBoxMesh.renderingGroupId = 1;
  87617. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  87618. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  87619. scene.removeMesh(this._debugBoxMesh);
  87620. }
  87621. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  87622. };
  87623. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  87624. if (!this._debugSphereMesh) {
  87625. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  87626. this._debugSphereMesh.renderingGroupId = 1;
  87627. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  87628. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  87629. scene.removeMesh(this._debugSphereMesh);
  87630. }
  87631. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  87632. };
  87633. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  87634. var mesh = null;
  87635. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  87636. mesh = this._getDebugBoxMesh(scene);
  87637. impostor.getBoxSizeToRef(mesh.scaling);
  87638. }
  87639. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  87640. mesh = this._getDebugSphereMesh(scene);
  87641. var radius = impostor.getRadius();
  87642. mesh.scaling.x = radius * 2;
  87643. mesh.scaling.y = radius * 2;
  87644. mesh.scaling.z = radius * 2;
  87645. }
  87646. return mesh;
  87647. };
  87648. /** Releases all resources */
  87649. PhysicsViewer.prototype.dispose = function () {
  87650. for (var i = 0; i < this._numMeshes; i++) {
  87651. this.hideImpostor(this._impostors[i]);
  87652. }
  87653. if (this._debugBoxMesh) {
  87654. this._debugBoxMesh.dispose();
  87655. }
  87656. if (this._debugSphereMesh) {
  87657. this._debugSphereMesh.dispose();
  87658. }
  87659. if (this._debugMaterial) {
  87660. this._debugMaterial.dispose();
  87661. }
  87662. this._impostors.length = 0;
  87663. this._scene = null;
  87664. this._physicsEnginePlugin = null;
  87665. };
  87666. return PhysicsViewer;
  87667. }());
  87668. Debug.PhysicsViewer = PhysicsViewer;
  87669. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87670. })(BABYLON || (BABYLON = {}));
  87671. //# sourceMappingURL=babylon.physicsViewer.js.map
  87672. var BABYLON;
  87673. (function (BABYLON) {
  87674. var BoundingBoxRenderer = /** @class */ (function () {
  87675. function BoundingBoxRenderer(scene) {
  87676. this.frontColor = new BABYLON.Color3(1, 1, 1);
  87677. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  87678. this.showBackLines = true;
  87679. this.renderList = new BABYLON.SmartArray(32);
  87680. this._vertexBuffers = {};
  87681. this._scene = scene;
  87682. }
  87683. BoundingBoxRenderer.prototype._prepareRessources = function () {
  87684. if (this._colorShader) {
  87685. return;
  87686. }
  87687. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  87688. attributes: [BABYLON.VertexBuffer.PositionKind],
  87689. uniforms: ["world", "viewProjection", "color"]
  87690. });
  87691. var engine = this._scene.getEngine();
  87692. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  87693. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  87694. this._createIndexBuffer();
  87695. };
  87696. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  87697. var engine = this._scene.getEngine();
  87698. 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]);
  87699. };
  87700. BoundingBoxRenderer.prototype._rebuild = function () {
  87701. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87702. if (vb) {
  87703. vb._rebuild();
  87704. }
  87705. this._createIndexBuffer();
  87706. };
  87707. BoundingBoxRenderer.prototype.reset = function () {
  87708. this.renderList.reset();
  87709. };
  87710. BoundingBoxRenderer.prototype.render = function () {
  87711. if (this.renderList.length === 0) {
  87712. return;
  87713. }
  87714. this._prepareRessources();
  87715. if (!this._colorShader.isReady()) {
  87716. return;
  87717. }
  87718. var engine = this._scene.getEngine();
  87719. engine.setDepthWrite(false);
  87720. this._colorShader._preBind();
  87721. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  87722. var boundingBox = this.renderList.data[boundingBoxIndex];
  87723. var min = boundingBox.minimum;
  87724. var max = boundingBox.maximum;
  87725. var diff = max.subtract(min);
  87726. var median = min.add(diff.scale(0.5));
  87727. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87728. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87729. .multiply(boundingBox.getWorldMatrix());
  87730. // VBOs
  87731. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87732. if (this.showBackLines) {
  87733. // Back
  87734. engine.setDepthFunctionToGreaterOrEqual();
  87735. this._scene.resetCachedMaterial();
  87736. this._colorShader.setColor4("color", this.backColor.toColor4());
  87737. this._colorShader.bind(worldMatrix);
  87738. // Draw order
  87739. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87740. }
  87741. // Front
  87742. engine.setDepthFunctionToLess();
  87743. this._scene.resetCachedMaterial();
  87744. this._colorShader.setColor4("color", this.frontColor.toColor4());
  87745. this._colorShader.bind(worldMatrix);
  87746. // Draw order
  87747. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87748. }
  87749. this._colorShader.unbind();
  87750. engine.setDepthFunctionToLessOrEqual();
  87751. engine.setDepthWrite(true);
  87752. };
  87753. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  87754. this._prepareRessources();
  87755. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  87756. return;
  87757. }
  87758. var engine = this._scene.getEngine();
  87759. engine.setDepthWrite(false);
  87760. engine.setColorWrite(false);
  87761. this._colorShader._preBind();
  87762. var boundingBox = mesh._boundingInfo.boundingBox;
  87763. var min = boundingBox.minimum;
  87764. var max = boundingBox.maximum;
  87765. var diff = max.subtract(min);
  87766. var median = min.add(diff.scale(0.5));
  87767. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87768. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87769. .multiply(boundingBox.getWorldMatrix());
  87770. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87771. engine.setDepthFunctionToLess();
  87772. this._scene.resetCachedMaterial();
  87773. this._colorShader.bind(worldMatrix);
  87774. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87775. this._colorShader.unbind();
  87776. engine.setDepthFunctionToLessOrEqual();
  87777. engine.setDepthWrite(true);
  87778. engine.setColorWrite(true);
  87779. };
  87780. BoundingBoxRenderer.prototype.dispose = function () {
  87781. if (!this._colorShader) {
  87782. return;
  87783. }
  87784. this.renderList.dispose();
  87785. this._colorShader.dispose();
  87786. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87787. if (buffer) {
  87788. buffer.dispose();
  87789. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87790. }
  87791. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87792. };
  87793. return BoundingBoxRenderer;
  87794. }());
  87795. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  87796. })(BABYLON || (BABYLON = {}));
  87797. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  87798. var BABYLON;
  87799. (function (BABYLON) {
  87800. /**
  87801. * Renders a layer on top of an existing scene
  87802. */
  87803. var UtilityLayerRenderer = /** @class */ (function () {
  87804. /**
  87805. * Instantiates a UtilityLayerRenderer
  87806. * @param originalScene the original scene that will be rendered on top of
  87807. */
  87808. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  87809. var _this = this;
  87810. this.originalScene = originalScene;
  87811. this._pointerCaptures = {};
  87812. this._lastPointerEvents = {};
  87813. /**
  87814. * If the utility layer should automatically be rendered on top of existing scene
  87815. */
  87816. this.shouldRender = true;
  87817. /**
  87818. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  87819. */
  87820. this.onlyCheckPointerDownEvents = true;
  87821. /**
  87822. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  87823. */
  87824. this.processAllEvents = false;
  87825. /**
  87826. * Observable raised when the pointer move from the utility layer scene to the main scene
  87827. */
  87828. this.onPointerOutObservable = new BABYLON.Observable();
  87829. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  87830. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  87831. originalScene.getEngine().scenes.pop();
  87832. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  87833. this.utilityLayerScene.detachControl();
  87834. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  87835. if (!_this.processAllEvents) {
  87836. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  87837. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  87838. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  87839. return;
  87840. }
  87841. }
  87842. var pointerEvent = (prePointerInfo.event);
  87843. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  87844. return;
  87845. }
  87846. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  87847. if (!prePointerInfo.ray && utilityScenePick) {
  87848. prePointerInfo.ray = utilityScenePick.ray;
  87849. }
  87850. // always fire the prepointer oversvable
  87851. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  87852. // allow every non pointer down event to flow to the utility layer
  87853. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  87854. if (!prePointerInfo.skipOnPointerObservable) {
  87855. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87856. }
  87857. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  87858. _this._pointerCaptures[pointerEvent.pointerId] = false;
  87859. }
  87860. return;
  87861. }
  87862. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  87863. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  87864. if (utilityScenePick && utilityScenePick.hit) {
  87865. if (!prePointerInfo.skipOnPointerObservable) {
  87866. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87867. }
  87868. prePointerInfo.skipOnPointerObservable = true;
  87869. }
  87870. }
  87871. else {
  87872. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  87873. var pointerEvent_1 = (prePointerInfo.event);
  87874. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  87875. if (originalScenePick && utilityScenePick) {
  87876. // No pick in utility scene
  87877. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  87878. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  87879. // We touched an utility mesh present in the main scene
  87880. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  87881. prePointerInfo.skipOnPointerObservable = true;
  87882. }
  87883. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87884. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  87885. }
  87886. }
  87887. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  87888. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  87889. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  87890. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  87891. }
  87892. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  87893. // We have a pick in both scenes but main is closer than utility
  87894. // We touched an utility mesh present in the main scene
  87895. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  87896. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  87897. prePointerInfo.skipOnPointerObservable = true;
  87898. }
  87899. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  87900. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  87901. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  87902. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  87903. }
  87904. }
  87905. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  87906. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  87907. }
  87908. }
  87909. }
  87910. });
  87911. // Render directly on top of existing scene without clearing
  87912. this.utilityLayerScene.autoClear = false;
  87913. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  87914. if (_this.shouldRender) {
  87915. _this.render();
  87916. }
  87917. });
  87918. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  87919. _this.dispose();
  87920. });
  87921. this._updateCamera();
  87922. }
  87923. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  87924. if (!prePointerInfo.skipOnPointerObservable) {
  87925. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  87926. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  87927. }
  87928. };
  87929. /**
  87930. * Renders the utility layers scene on top of the original scene
  87931. */
  87932. UtilityLayerRenderer.prototype.render = function () {
  87933. this._updateCamera();
  87934. this.utilityLayerScene.render(false);
  87935. };
  87936. /**
  87937. * Disposes of the renderer
  87938. */
  87939. UtilityLayerRenderer.prototype.dispose = function () {
  87940. this.onPointerOutObservable.clear();
  87941. if (this._afterRenderObserver) {
  87942. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  87943. }
  87944. if (this._sceneDisposeObserver) {
  87945. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  87946. }
  87947. if (this._originalPointerObserver) {
  87948. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  87949. }
  87950. this.utilityLayerScene.dispose();
  87951. };
  87952. UtilityLayerRenderer.prototype._updateCamera = function () {
  87953. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  87954. };
  87955. return UtilityLayerRenderer;
  87956. }());
  87957. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  87958. })(BABYLON || (BABYLON = {}));
  87959. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  87960. //# sourceMappingURL=babylon.behavior.js.map
  87961. var BABYLON;
  87962. (function (BABYLON) {
  87963. /**
  87964. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  87965. */
  87966. var PointerDragBehavior = /** @class */ (function () {
  87967. /**
  87968. * Creates a pointer drag behavior that can be attached to a mesh
  87969. * @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)
  87970. */
  87971. function PointerDragBehavior(options) {
  87972. this.options = options;
  87973. /**
  87974. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  87975. */
  87976. this.currentDraggingPointerID = -1;
  87977. /**
  87978. * If the behavior is currently in a dragging state
  87979. */
  87980. this.dragging = false;
  87981. /**
  87982. * 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)
  87983. */
  87984. this.dragDeltaRatio = 0.2;
  87985. /**
  87986. * If the drag plane orientation should be updated during the dragging (Default: true)
  87987. */
  87988. this.updateDragPlane = true;
  87989. // Debug mode will display drag planes to help visualize behavior
  87990. this._debugMode = false;
  87991. this._moving = false;
  87992. /**
  87993. * Fires each time the attached mesh is dragged with the pointer
  87994. * * delta between last drag position and current drag position in world space
  87995. * * dragDistance along the drag axis
  87996. * * dragPlaneNormal normal of the current drag plane used during the drag
  87997. * * dragPlanePoint in world space where the drag intersects the drag plane
  87998. */
  87999. this.onDragObservable = new BABYLON.Observable();
  88000. /**
  88001. * Fires each time a drag begins (eg. mouse down on mesh)
  88002. */
  88003. this.onDragStartObservable = new BABYLON.Observable();
  88004. /**
  88005. * Fires each time a drag ends (eg. mouse release after drag)
  88006. */
  88007. this.onDragEndObservable = new BABYLON.Observable();
  88008. /**
  88009. * If the attached mesh should be moved when dragged
  88010. */
  88011. this.moveAttached = true;
  88012. /**
  88013. * If the drag behavior will react to drag events (Default: true)
  88014. */
  88015. this.enabled = true;
  88016. /**
  88017. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  88018. */
  88019. this.useObjectOrienationForDragging = true;
  88020. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  88021. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  88022. // Variables to avoid instantiation in the below method
  88023. this._pointA = new BABYLON.Vector3(0, 0, 0);
  88024. this._pointB = new BABYLON.Vector3(0, 0, 0);
  88025. this._pointC = new BABYLON.Vector3(0, 0, 0);
  88026. this._lineA = new BABYLON.Vector3(0, 0, 0);
  88027. this._lineB = new BABYLON.Vector3(0, 0, 0);
  88028. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  88029. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  88030. var optionCount = 0;
  88031. if (options === undefined) {
  88032. options = {};
  88033. }
  88034. if (options.dragAxis) {
  88035. optionCount++;
  88036. }
  88037. if (options.dragPlaneNormal) {
  88038. optionCount++;
  88039. }
  88040. if (optionCount > 1) {
  88041. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  88042. }
  88043. }
  88044. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  88045. /**
  88046. * The name of the behavior
  88047. */
  88048. get: function () {
  88049. return "PointerDrag";
  88050. },
  88051. enumerable: true,
  88052. configurable: true
  88053. });
  88054. /**
  88055. * Initializes the behavior
  88056. */
  88057. PointerDragBehavior.prototype.init = function () { };
  88058. /**
  88059. * Attaches the drag behavior the passed in mesh
  88060. * @param ownerNode The mesh that will be dragged around once attached
  88061. */
  88062. PointerDragBehavior.prototype.attach = function (ownerNode) {
  88063. var _this = this;
  88064. this._scene = ownerNode.getScene();
  88065. this._attachedNode = ownerNode;
  88066. // Initialize drag plane to not interfere with existing scene
  88067. if (!PointerDragBehavior._planeScene) {
  88068. if (this._debugMode) {
  88069. PointerDragBehavior._planeScene = this._scene;
  88070. }
  88071. else {
  88072. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  88073. this._scene.getEngine().scenes.pop();
  88074. }
  88075. }
  88076. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  88077. // State of the drag
  88078. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  88079. var delta = new BABYLON.Vector3(0, 0, 0);
  88080. var dragLength = 0;
  88081. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  88082. var pickPredicate = function (m) {
  88083. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  88084. };
  88085. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88086. if (!_this.enabled) {
  88087. return;
  88088. }
  88089. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88090. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88091. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  88092. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88093. if (pickedPoint) {
  88094. _this.dragging = true;
  88095. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88096. _this.lastDragPosition.copyFrom(pickedPoint);
  88097. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  88098. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  88099. }
  88100. }
  88101. }
  88102. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88103. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88104. _this.releaseDrag();
  88105. }
  88106. }
  88107. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88108. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  88109. _this._moving = true;
  88110. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88111. if (pickedPoint) {
  88112. if (_this.updateDragPlane) {
  88113. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  88114. }
  88115. // depending on the drag mode option drag accordingly
  88116. if (_this.options.dragAxis) {
  88117. // Convert local drag axis to world
  88118. BABYLON.Vector3.TransformCoordinatesToRef(_this.options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  88119. // Project delta drag from the drag plane onto the drag axis
  88120. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  88121. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  88122. _this._worldDragAxis.scaleToRef(dragLength, delta);
  88123. }
  88124. else {
  88125. dragLength = delta.length();
  88126. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  88127. }
  88128. targetPosition.addInPlace(delta);
  88129. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  88130. _this.lastDragPosition.copyFrom(pickedPoint);
  88131. }
  88132. }
  88133. }
  88134. });
  88135. this._scene.onBeforeRenderObservable.add(function () {
  88136. if (_this._moving && _this.moveAttached) {
  88137. // Slowly move mesh to avoid jitter
  88138. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  88139. _this._tmpVector.scaleInPlace(0.2);
  88140. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  88141. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  88142. }
  88143. });
  88144. };
  88145. PointerDragBehavior.prototype.releaseDrag = function () {
  88146. this.dragging = false;
  88147. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  88148. this.currentDraggingPointerID = -1;
  88149. this._moving = false;
  88150. };
  88151. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  88152. var _this = this;
  88153. if (!ray) {
  88154. return null;
  88155. }
  88156. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  88157. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  88158. return pickResult.pickedPoint;
  88159. }
  88160. else {
  88161. return null;
  88162. }
  88163. };
  88164. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  88165. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  88166. this._pointA.copyFrom(dragPlanePosition);
  88167. if (this.options.dragAxis) {
  88168. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragAxis);
  88169. // Calculate plane normal in direction of camera but perpendicular to drag axis
  88170. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  88171. ray.origin.subtractToRef(this._pointA, this._pointC);
  88172. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  88173. // Get perpendicular line from direction to camera and drag axis
  88174. this._pointB.subtractToRef(this._pointA, this._lineA);
  88175. this._pointC.subtractToRef(this._pointA, this._lineB);
  88176. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  88177. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  88178. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  88179. this._lookAt.normalize();
  88180. this._dragPlane.position.copyFrom(this._pointA);
  88181. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  88182. this._dragPlane.lookAt(this._lookAt);
  88183. }
  88184. else if (this.options.dragPlaneNormal) {
  88185. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragPlaneNormal);
  88186. this._dragPlane.position.copyFrom(this._pointA);
  88187. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  88188. this._dragPlane.lookAt(this._lookAt);
  88189. }
  88190. else {
  88191. this._dragPlane.position.copyFrom(this._pointA);
  88192. this._dragPlane.lookAt(ray.origin);
  88193. }
  88194. this._dragPlane.computeWorldMatrix(true);
  88195. };
  88196. /**
  88197. * Detaches the behavior from the mesh
  88198. */
  88199. PointerDragBehavior.prototype.detach = function () {
  88200. if (this._pointerObserver) {
  88201. this._scene.onPointerObservable.remove(this._pointerObserver);
  88202. }
  88203. };
  88204. return PointerDragBehavior;
  88205. }());
  88206. BABYLON.PointerDragBehavior = PointerDragBehavior;
  88207. })(BABYLON || (BABYLON = {}));
  88208. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  88209. var BABYLON;
  88210. (function (BABYLON) {
  88211. /**
  88212. * A behavior that when attached to a mesh will allow the mesh to be scaled
  88213. */
  88214. var MultiPointerScaleBehavior = /** @class */ (function () {
  88215. function MultiPointerScaleBehavior() {
  88216. this._startDistance = 0;
  88217. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  88218. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  88219. this._sceneRenderObserver = null;
  88220. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  88221. this._dragBehaviorA.moveAttached = false;
  88222. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  88223. this._dragBehaviorB.moveAttached = false;
  88224. }
  88225. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  88226. /**
  88227. * The name of the behavior
  88228. */
  88229. get: function () {
  88230. return "MultiPointerScale";
  88231. },
  88232. enumerable: true,
  88233. configurable: true
  88234. });
  88235. /**
  88236. * Initializes the behavior
  88237. */
  88238. MultiPointerScaleBehavior.prototype.init = function () { };
  88239. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  88240. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  88241. };
  88242. /**
  88243. * Attaches the scale behavior the passed in mesh
  88244. * @param ownerNode The mesh that will be scaled around once attached
  88245. */
  88246. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  88247. var _this = this;
  88248. this._ownerNode = ownerNode;
  88249. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  88250. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  88251. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88252. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  88253. _this._dragBehaviorA.releaseDrag();
  88254. }
  88255. else {
  88256. _this._initialScale.copyFrom(ownerNode.scaling);
  88257. _this._startDistance = _this._getCurrentDistance();
  88258. }
  88259. }
  88260. });
  88261. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  88262. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88263. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  88264. _this._dragBehaviorB.releaseDrag();
  88265. }
  88266. else {
  88267. _this._initialScale.copyFrom(ownerNode.scaling);
  88268. _this._startDistance = _this._getCurrentDistance();
  88269. }
  88270. }
  88271. });
  88272. // Once both drag behaviors are active scale based on the distance between the two pointers
  88273. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  88274. behavior.onDragObservable.add(function () {
  88275. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88276. var ratio = _this._getCurrentDistance() / _this._startDistance;
  88277. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  88278. }
  88279. });
  88280. });
  88281. ownerNode.addBehavior(this._dragBehaviorA);
  88282. ownerNode.addBehavior(this._dragBehaviorB);
  88283. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  88284. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  88285. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88286. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  88287. if (change.length() > 0.01) {
  88288. ownerNode.scaling.addInPlace(change);
  88289. }
  88290. }
  88291. });
  88292. };
  88293. /**
  88294. * Detaches the behavior from the mesh
  88295. */
  88296. MultiPointerScaleBehavior.prototype.detach = function () {
  88297. var _this = this;
  88298. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  88299. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  88300. behavior.onDragStartObservable.clear();
  88301. behavior.onDragObservable.clear();
  88302. _this._ownerNode.removeBehavior(behavior);
  88303. });
  88304. };
  88305. return MultiPointerScaleBehavior;
  88306. }());
  88307. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  88308. })(BABYLON || (BABYLON = {}));
  88309. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  88310. var BABYLON;
  88311. (function (BABYLON) {
  88312. /**
  88313. * 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
  88314. */
  88315. var SixDofDragBehavior = /** @class */ (function () {
  88316. function SixDofDragBehavior() {
  88317. this._sceneRenderObserver = null;
  88318. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  88319. this._moving = false;
  88320. this._startingOrientation = new BABYLON.Quaternion();
  88321. /**
  88322. * 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)
  88323. */
  88324. this.zDragFactor = 5;
  88325. /**
  88326. * If the behavior is currently in a dragging state
  88327. */
  88328. this.dragging = false;
  88329. /**
  88330. * 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)
  88331. */
  88332. this.dragDeltaRatio = 0.2;
  88333. /**
  88334. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88335. */
  88336. this.currentDraggingPointerID = -1;
  88337. }
  88338. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  88339. /**
  88340. * The name of the behavior
  88341. */
  88342. get: function () {
  88343. return "SixDofDrag";
  88344. },
  88345. enumerable: true,
  88346. configurable: true
  88347. });
  88348. /**
  88349. * Initializes the behavior
  88350. */
  88351. SixDofDragBehavior.prototype.init = function () { };
  88352. /**
  88353. * Attaches the scale behavior the passed in mesh
  88354. * @param ownerNode The mesh that will be scaled around once attached
  88355. */
  88356. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  88357. var _this = this;
  88358. this._ownerNode = ownerNode;
  88359. this._scene = this._ownerNode.getScene();
  88360. if (!SixDofDragBehavior._virtualScene) {
  88361. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  88362. this._scene.getEngine().scenes.pop();
  88363. }
  88364. var pickedMesh = null;
  88365. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  88366. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  88367. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  88368. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  88369. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  88370. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  88371. var pickPredicate = function (m) {
  88372. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  88373. };
  88374. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88375. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88376. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88377. pickedMesh = pointerInfo.pickInfo.pickedMesh;
  88378. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  88379. // Set position and orientation of the controller
  88380. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  88381. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  88382. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  88383. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88384. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  88385. if (!pickedMesh.rotationQuaternion) {
  88386. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  88387. }
  88388. var oldParent = pickedMesh.parent;
  88389. pickedMesh.setParent(null);
  88390. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  88391. pickedMesh.setParent(oldParent);
  88392. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  88393. // Update state
  88394. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  88395. _this.dragging = true;
  88396. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88397. }
  88398. }
  88399. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88400. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88401. _this.dragging = false;
  88402. _this._moving = false;
  88403. _this.currentDraggingPointerID = -1;
  88404. pickedMesh = null;
  88405. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88406. }
  88407. }
  88408. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88409. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  88410. // Calculate controller drag distance in controller space
  88411. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  88412. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  88413. var localOriginDragDifference = BABYLON.Vector3.TransformCoordinates(originDragDifference, BABYLON.Matrix.Invert(_this._virtualOriginMesh.getWorldMatrix().getRotationMatrix()));
  88414. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  88415. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  88416. var zDragDistance = BABYLON.Vector3.Dot(localOriginDragDifference, _this._virtualOriginMesh.position.normalizeToNew());
  88417. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? zDragDistance * _this.zDragFactor : zDragDistance * _this.zDragFactor * _this._virtualDragMesh.position.z;
  88418. if (_this._virtualDragMesh.position.z < 0) {
  88419. _this._virtualDragMesh.position.z = 0;
  88420. }
  88421. // Update the controller position
  88422. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  88423. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  88424. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88425. // Move the virtualObjectsPosition into the picked mesh's space if needed
  88426. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  88427. if (pickedMesh.parent) {
  88428. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  88429. }
  88430. if (!_this._moving) {
  88431. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  88432. }
  88433. _this._moving = true;
  88434. }
  88435. }
  88436. });
  88437. var tmpQuaternion = new BABYLON.Quaternion();
  88438. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  88439. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  88440. if (_this.dragging && _this._moving && pickedMesh) {
  88441. // Slowly move mesh to avoid jitter
  88442. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  88443. // Get change in rotation
  88444. tmpQuaternion.copyFrom(_this._startingOrientation);
  88445. tmpQuaternion.x = -tmpQuaternion.x;
  88446. tmpQuaternion.y = -tmpQuaternion.y;
  88447. tmpQuaternion.z = -tmpQuaternion.z;
  88448. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  88449. // Convert change in rotation to only y axis rotation
  88450. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  88451. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  88452. // Slowly move mesh to avoid jitter
  88453. var oldParent = pickedMesh.parent;
  88454. pickedMesh.setParent(null);
  88455. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  88456. pickedMesh.setParent(oldParent);
  88457. }
  88458. });
  88459. };
  88460. /**
  88461. * Detaches the behavior from the mesh
  88462. */
  88463. SixDofDragBehavior.prototype.detach = function () {
  88464. this._scene.onPointerObservable.remove(this._pointerObserver);
  88465. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  88466. this._virtualOriginMesh.dispose();
  88467. this._virtualDragMesh.dispose();
  88468. };
  88469. return SixDofDragBehavior;
  88470. }());
  88471. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  88472. })(BABYLON || (BABYLON = {}));
  88473. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  88474. var BABYLON;
  88475. (function (BABYLON) {
  88476. /**
  88477. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  88478. */
  88479. var Gizmo = /** @class */ (function () {
  88480. /**
  88481. * Creates a gizmo
  88482. * @param gizmoLayer The utility layer the gizmo will be added to
  88483. */
  88484. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  88485. var _this = this;
  88486. this.gizmoLayer = gizmoLayer;
  88487. /**
  88488. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  88489. */
  88490. this.updateGizmoRotationToMatchAttachedMesh = true;
  88491. /**
  88492. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  88493. */
  88494. this.updateGizmoPositionToMatchAttachedMesh = true;
  88495. /**
  88496. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  88497. */
  88498. this._updateScale = true;
  88499. this._interactionsEnabled = true;
  88500. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  88501. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  88502. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  88503. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 3;
  88504. _this._rootMesh.scaling.set(dist, dist, dist);
  88505. }
  88506. if (_this.attachedMesh) {
  88507. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  88508. if (!_this._rootMesh.rotationQuaternion) {
  88509. _this._rootMesh.rotationQuaternion = new BABYLON.Quaternion();
  88510. }
  88511. BABYLON.Quaternion.FromRotationMatrixToRef(_this.attachedMesh.getWorldMatrix().getRotationMatrix(), _this._rootMesh.rotationQuaternion);
  88512. }
  88513. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  88514. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  88515. }
  88516. }
  88517. });
  88518. }
  88519. Gizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88520. };
  88521. Object.defineProperty(Gizmo.prototype, "interactionsEnabled", {
  88522. get: function () {
  88523. return this._interactionsEnabled;
  88524. },
  88525. /**
  88526. * If interactions are enabled with this gizmo. (eg. dragging/rotation)
  88527. */
  88528. set: function (value) {
  88529. this._interactionsEnabled = value;
  88530. this._onInteractionsEnabledChanged(value);
  88531. },
  88532. enumerable: true,
  88533. configurable: true
  88534. });
  88535. /**
  88536. * Disposes of the gizmo
  88537. */
  88538. Gizmo.prototype.dispose = function () {
  88539. this._rootMesh.dispose();
  88540. if (this._beforeRenderObserver) {
  88541. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  88542. }
  88543. };
  88544. return Gizmo;
  88545. }());
  88546. BABYLON.Gizmo = Gizmo;
  88547. })(BABYLON || (BABYLON = {}));
  88548. //# sourceMappingURL=babylon.gizmo.js.map
  88549. var BABYLON;
  88550. (function (BABYLON) {
  88551. /**
  88552. * Single axis drag gizmo
  88553. */
  88554. var AxisDragGizmo = /** @class */ (function (_super) {
  88555. __extends(AxisDragGizmo, _super);
  88556. /**
  88557. * Creates an AxisDragGizmo
  88558. * @param gizmoLayer The utility layer the gizmo will be added to
  88559. * @param dragAxis The axis which the gizmo will be able to drag on
  88560. * @param color The color of the gizmo
  88561. */
  88562. function AxisDragGizmo(gizmoLayer, dragAxis, color) {
  88563. var _this = _super.call(this, gizmoLayer) || this;
  88564. _this.updateGizmoRotationToMatchAttachedMesh = false;
  88565. // Create Material
  88566. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88567. coloredMaterial.disableLighting = true;
  88568. coloredMaterial.emissiveColor = color;
  88569. // Build mesh on root node
  88570. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88571. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88572. _this._rootMesh.addChild(arrowMesh);
  88573. _this._rootMesh.addChild(arrowTail);
  88574. // Position arrow pointing in its drag axis
  88575. arrowMesh.scaling.scaleInPlace(0.1);
  88576. arrowMesh.material = coloredMaterial;
  88577. arrowMesh.rotation.x = Math.PI / 2;
  88578. arrowMesh.position.z += 0.3;
  88579. arrowTail.rotation.x = Math.PI / 2;
  88580. arrowTail.material = coloredMaterial;
  88581. arrowTail.position.z += 0.2;
  88582. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  88583. // Add drag behavior to handle events when the gizmo is dragged
  88584. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: new BABYLON.Vector3(0, 0, 1) });
  88585. _this._dragBehavior.moveAttached = false;
  88586. _this._rootMesh.addBehavior(_this._dragBehavior);
  88587. _this._dragBehavior.onDragObservable.add(function (event) {
  88588. if (!_this.interactionsEnabled) {
  88589. return;
  88590. }
  88591. if (_this.attachedMesh) {
  88592. _this.attachedMesh.position.addInPlace(event.delta);
  88593. }
  88594. });
  88595. return _this;
  88596. }
  88597. AxisDragGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88598. this._dragBehavior.enabled = value;
  88599. };
  88600. /**
  88601. * Disposes of the gizmo
  88602. */
  88603. AxisDragGizmo.prototype.dispose = function () {
  88604. this._dragBehavior.detach();
  88605. _super.prototype.dispose.call(this);
  88606. };
  88607. return AxisDragGizmo;
  88608. }(BABYLON.Gizmo));
  88609. BABYLON.AxisDragGizmo = AxisDragGizmo;
  88610. })(BABYLON || (BABYLON = {}));
  88611. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  88612. var BABYLON;
  88613. (function (BABYLON) {
  88614. /**
  88615. * Single axis scale gizmo
  88616. */
  88617. var AxisScaleGizmo = /** @class */ (function (_super) {
  88618. __extends(AxisScaleGizmo, _super);
  88619. /**
  88620. * Creates an AxisScaleGizmo
  88621. * @param gizmoLayer The utility layer the gizmo will be added to
  88622. * @param dragAxis The axis which the gizmo will be able to scale on
  88623. * @param color The color of the gizmo
  88624. */
  88625. function AxisScaleGizmo(gizmoLayer, dragAxis, color) {
  88626. var _this = _super.call(this, gizmoLayer) || this;
  88627. _this.updateGizmoRotationToMatchAttachedMesh = false;
  88628. // Create Material
  88629. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88630. coloredMaterial.disableLighting = true;
  88631. coloredMaterial.emissiveColor = color;
  88632. // Build mesh on root node
  88633. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 1 }, gizmoLayer.utilityLayerScene);
  88634. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88635. _this._rootMesh.addChild(arrowMesh);
  88636. _this._rootMesh.addChild(arrowTail);
  88637. // Position arrow pointing in its drag axis
  88638. arrowMesh.scaling.scaleInPlace(0.1);
  88639. arrowMesh.material = coloredMaterial;
  88640. arrowMesh.rotation.x = Math.PI / 2;
  88641. arrowMesh.position.z += 0.3;
  88642. arrowTail.rotation.x = Math.PI / 2;
  88643. arrowTail.material = coloredMaterial;
  88644. arrowTail.position.z += 0.2;
  88645. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  88646. // Add drag behavior to handle events when the gizmo is dragged
  88647. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: new BABYLON.Vector3(0, 0, 1) });
  88648. _this._dragBehavior.moveAttached = false;
  88649. _this._rootMesh.addBehavior(_this._dragBehavior);
  88650. _this._dragBehavior.onDragObservable.add(function (event) {
  88651. if (!_this.interactionsEnabled) {
  88652. return;
  88653. }
  88654. if (_this.attachedMesh) {
  88655. _this.attachedMesh.scaling.addInPlace(event.delta);
  88656. }
  88657. });
  88658. return _this;
  88659. }
  88660. AxisScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88661. this._dragBehavior.enabled = value;
  88662. };
  88663. /**
  88664. * Disposes of the gizmo
  88665. */
  88666. AxisScaleGizmo.prototype.dispose = function () {
  88667. this._dragBehavior.detach();
  88668. _super.prototype.dispose.call(this);
  88669. };
  88670. return AxisScaleGizmo;
  88671. }(BABYLON.Gizmo));
  88672. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  88673. })(BABYLON || (BABYLON = {}));
  88674. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  88675. var BABYLON;
  88676. (function (BABYLON) {
  88677. /**
  88678. * Single plane rotation gizmo
  88679. */
  88680. var PlaneRotationGizmo = /** @class */ (function (_super) {
  88681. __extends(PlaneRotationGizmo, _super);
  88682. /**
  88683. * Creates a PlaneRotationGizmo
  88684. * @param gizmoLayer The utility layer the gizmo will be added to
  88685. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  88686. * @param color The color of the gizmo
  88687. */
  88688. function PlaneRotationGizmo(gizmoLayer, planeNormal, color) {
  88689. var _this = _super.call(this, gizmoLayer) || this;
  88690. _this.updateGizmoRotationToMatchAttachedMesh = false;
  88691. // Create Material
  88692. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88693. coloredMaterial.disableLighting = true;
  88694. coloredMaterial.emissiveColor = color;
  88695. // Build mesh on root node
  88696. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.3, 20, gizmoLayer.utilityLayerScene, false);
  88697. _this._rootMesh.addChild(rotationMesh);
  88698. // Position arrow pointing in its drag axis
  88699. rotationMesh.scaling.scaleInPlace(0.1);
  88700. rotationMesh.material = coloredMaterial;
  88701. rotationMesh.rotation.x = Math.PI / 2;
  88702. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  88703. // Add drag behavior to handle events when the gizmo is dragged
  88704. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: new BABYLON.Vector3(0, 0, 1) });
  88705. _this._dragBehavior.moveAttached = false;
  88706. _this._rootMesh.addBehavior(_this._dragBehavior);
  88707. var lastDragPosition = null;
  88708. _this._dragBehavior.onDragStartObservable.add(function (e) {
  88709. if (!_this.interactionsEnabled) {
  88710. return;
  88711. }
  88712. lastDragPosition = e.dragPlanePoint;
  88713. });
  88714. _this._dragBehavior.onDragObservable.add(function (event) {
  88715. if (!_this.interactionsEnabled) {
  88716. return;
  88717. }
  88718. if (_this.attachedMesh && lastDragPosition) {
  88719. if (!_this.attachedMesh.rotationQuaternion) {
  88720. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  88721. }
  88722. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  88723. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  88724. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  88725. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  88726. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  88727. var angle = Math.atan2(cross.length(), dot);
  88728. var up = planeNormal.clone();
  88729. // Flip up vector depending on which side the camera is on
  88730. if (gizmoLayer.utilityLayerScene.activeCamera) {
  88731. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  88732. if (BABYLON.Vector3.Dot(camVec, up) > 0) {
  88733. up.scaleInPlace(-1);
  88734. }
  88735. }
  88736. var halfCircleSide = BABYLON.Vector3.Dot(up, cross) > 0.0;
  88737. if (halfCircleSide)
  88738. angle = -angle;
  88739. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  88740. var quaternionCoefficient = Math.sin(angle / 2);
  88741. var amountToRotate = new BABYLON.Quaternion(up.x * quaternionCoefficient, up.y * quaternionCoefficient, up.z * quaternionCoefficient, Math.cos(angle / 2));
  88742. // Rotate selected mesh quaternion over fixed axis
  88743. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  88744. lastDragPosition = event.dragPlanePoint;
  88745. }
  88746. });
  88747. return _this;
  88748. }
  88749. PlaneRotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88750. this._dragBehavior.enabled = value;
  88751. };
  88752. /**
  88753. * Disposes of the gizmo
  88754. */
  88755. PlaneRotationGizmo.prototype.dispose = function () {
  88756. this._dragBehavior.detach();
  88757. _super.prototype.dispose.call(this);
  88758. };
  88759. return PlaneRotationGizmo;
  88760. }(BABYLON.Gizmo));
  88761. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  88762. })(BABYLON || (BABYLON = {}));
  88763. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  88764. var BABYLON;
  88765. (function (BABYLON) {
  88766. /**
  88767. * Gizmo that enables dragging a mesh along 3 axis
  88768. */
  88769. var PositionGizmo = /** @class */ (function (_super) {
  88770. __extends(PositionGizmo, _super);
  88771. /**
  88772. * Creates a PositionGizmo
  88773. * @param gizmoLayer The utility layer the gizmo will be added to
  88774. */
  88775. function PositionGizmo(gizmoLayer) {
  88776. var _this = _super.call(this, gizmoLayer) || this;
  88777. _this._xDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  88778. _this._yDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  88779. _this._zDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  88780. return _this;
  88781. }
  88782. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  88783. set: function (mesh) {
  88784. this._xDrag.attachedMesh = mesh;
  88785. this._yDrag.attachedMesh = mesh;
  88786. this._zDrag.attachedMesh = mesh;
  88787. },
  88788. enumerable: true,
  88789. configurable: true
  88790. });
  88791. PositionGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88792. this._xDrag.interactionsEnabled = value;
  88793. this._yDrag.interactionsEnabled = value;
  88794. this._zDrag.interactionsEnabled = value;
  88795. };
  88796. /**
  88797. * Disposes of the gizmo
  88798. */
  88799. PositionGizmo.prototype.dispose = function () {
  88800. this._xDrag.dispose();
  88801. this._yDrag.dispose();
  88802. this._zDrag.dispose();
  88803. };
  88804. return PositionGizmo;
  88805. }(BABYLON.Gizmo));
  88806. BABYLON.PositionGizmo = PositionGizmo;
  88807. })(BABYLON || (BABYLON = {}));
  88808. //# sourceMappingURL=babylon.positionGizmo.js.map
  88809. var BABYLON;
  88810. (function (BABYLON) {
  88811. /**
  88812. * Gizmo that enables rotating a mesh along 3 axis
  88813. */
  88814. var RotationGizmo = /** @class */ (function (_super) {
  88815. __extends(RotationGizmo, _super);
  88816. /**
  88817. * Creates a RotationGizmo
  88818. * @param gizmoLayer The utility layer the gizmo will be added to
  88819. */
  88820. function RotationGizmo(gizmoLayer) {
  88821. var _this = _super.call(this, gizmoLayer) || this;
  88822. _this._xDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  88823. _this._yDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  88824. _this._zDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  88825. return _this;
  88826. }
  88827. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  88828. set: function (mesh) {
  88829. this._xDrag.attachedMesh = mesh;
  88830. this._yDrag.attachedMesh = mesh;
  88831. this._zDrag.attachedMesh = mesh;
  88832. },
  88833. enumerable: true,
  88834. configurable: true
  88835. });
  88836. RotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88837. this._xDrag.interactionsEnabled = value;
  88838. this._yDrag.interactionsEnabled = value;
  88839. this._zDrag.interactionsEnabled = value;
  88840. };
  88841. /**
  88842. * Disposes of the gizmo
  88843. */
  88844. RotationGizmo.prototype.dispose = function () {
  88845. this._xDrag.dispose();
  88846. this._yDrag.dispose();
  88847. this._zDrag.dispose();
  88848. };
  88849. return RotationGizmo;
  88850. }(BABYLON.Gizmo));
  88851. BABYLON.RotationGizmo = RotationGizmo;
  88852. })(BABYLON || (BABYLON = {}));
  88853. //# sourceMappingURL=babylon.rotationGizmo.js.map
  88854. var BABYLON;
  88855. (function (BABYLON) {
  88856. /**
  88857. * Gizmo that enables scaling a mesh along 3 axis
  88858. */
  88859. var ScaleGizmo = /** @class */ (function (_super) {
  88860. __extends(ScaleGizmo, _super);
  88861. /**
  88862. * Creates a ScaleGizmo
  88863. * @param gizmoLayer The utility layer the gizmo will be added to
  88864. */
  88865. function ScaleGizmo(gizmoLayer) {
  88866. var _this = _super.call(this, gizmoLayer) || this;
  88867. _this._xDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  88868. _this._yDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  88869. _this._zDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  88870. return _this;
  88871. }
  88872. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  88873. set: function (mesh) {
  88874. this._xDrag.attachedMesh = mesh;
  88875. this._yDrag.attachedMesh = mesh;
  88876. this._zDrag.attachedMesh = mesh;
  88877. },
  88878. enumerable: true,
  88879. configurable: true
  88880. });
  88881. ScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88882. this._xDrag.interactionsEnabled = value;
  88883. this._yDrag.interactionsEnabled = value;
  88884. this._zDrag.interactionsEnabled = value;
  88885. };
  88886. /**
  88887. * Disposes of the gizmo
  88888. */
  88889. ScaleGizmo.prototype.dispose = function () {
  88890. this._xDrag.dispose();
  88891. this._yDrag.dispose();
  88892. this._zDrag.dispose();
  88893. };
  88894. return ScaleGizmo;
  88895. }(BABYLON.Gizmo));
  88896. BABYLON.ScaleGizmo = ScaleGizmo;
  88897. })(BABYLON || (BABYLON = {}));
  88898. //# sourceMappingURL=babylon.scaleGizmo.js.map
  88899. var BABYLON;
  88900. (function (BABYLON) {
  88901. /**
  88902. * Bounding box gizmo
  88903. */
  88904. var BoundingBoxGizmo = /** @class */ (function (_super) {
  88905. __extends(BoundingBoxGizmo, _super);
  88906. /**
  88907. * Creates an BoundingBoxGizmo
  88908. * @param gizmoLayer The utility layer the gizmo will be added to
  88909. * @param color The color of the gizmo
  88910. */
  88911. function BoundingBoxGizmo(gizmoLayer, color) {
  88912. var _this = _super.call(this, gizmoLayer) || this;
  88913. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  88914. _this._renderObserver = null;
  88915. _this._pointerObserver = null;
  88916. _this._scaleDragSpeed = 0.2;
  88917. _this._tmpQuaternion = new BABYLON.Quaternion();
  88918. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  88919. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  88920. _this._updateScale = false;
  88921. // Create Materials
  88922. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88923. coloredMaterial.disableLighting = true;
  88924. coloredMaterial.emissiveColor = color;
  88925. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88926. hoverColoredMaterial.disableLighting = true;
  88927. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  88928. // Build bounding box out of lines
  88929. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  88930. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  88931. var lines = [];
  88932. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  88933. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  88934. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  88935. 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));
  88936. 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));
  88937. 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));
  88938. 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));
  88939. 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));
  88940. 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));
  88941. 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));
  88942. 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));
  88943. 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));
  88944. lines.forEach(function (l) {
  88945. l.color = color;
  88946. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  88947. l.isPickable = false;
  88948. _this._lineBoundingBox.addChild(l);
  88949. });
  88950. _this._rootMesh.addChild(_this._lineBoundingBox);
  88951. // Create rotation spheres
  88952. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  88953. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  88954. var _loop_1 = function (i_1) {
  88955. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 0.1 }, gizmoLayer.utilityLayerScene);
  88956. sphere.rotationQuaternion = new BABYLON.Quaternion();
  88957. sphere.material = coloredMaterial;
  88958. // Drag behavior
  88959. _dragBehavior = new BABYLON.PointerDragBehavior({});
  88960. _dragBehavior.moveAttached = false;
  88961. _dragBehavior.updateDragPlane = false;
  88962. sphere.addBehavior(_dragBehavior);
  88963. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  88964. var totalTurnAmountOfDrag = 0;
  88965. _dragBehavior.onDragStartObservable.add(function (event) {
  88966. startingTurnDirection.copyFrom(sphere.forward);
  88967. totalTurnAmountOfDrag = 0;
  88968. });
  88969. _dragBehavior.onDragObservable.add(function (event) {
  88970. if (_this.attachedMesh) {
  88971. var worldDragDirection = startingTurnDirection;
  88972. // Project the world right on to the drag plane
  88973. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  88974. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  88975. // project drag delta on to the resulting drag axis and rotate based on that
  88976. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  88977. // Rotate based on axis
  88978. if (!_this.attachedMesh.rotationQuaternion) {
  88979. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  88980. }
  88981. // Do not allow the object to turn more than a full circle
  88982. totalTurnAmountOfDrag += projectDist;
  88983. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  88984. if (i_1 >= 8) {
  88985. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  88986. }
  88987. else if (i_1 >= 4) {
  88988. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  88989. }
  88990. else {
  88991. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  88992. }
  88993. _this.attachedMesh.rotationQuaternion.multiplyInPlace(_this._tmpQuaternion);
  88994. }
  88995. }
  88996. });
  88997. // Selection/deselection
  88998. _dragBehavior.onDragStartObservable.add(function () {
  88999. _this._selectNode(sphere);
  89000. });
  89001. _dragBehavior.onDragEndObservable.add(function () {
  89002. _this._selectNode(null);
  89003. });
  89004. this_1._rotateSpheresParent.addChild(sphere);
  89005. };
  89006. var this_1 = this, _dragBehavior;
  89007. for (var i_1 = 0; i_1 < 12; i_1++) {
  89008. _loop_1(i_1);
  89009. }
  89010. _this._rootMesh.addChild(_this._rotateSpheresParent);
  89011. // Create scale cubes
  89012. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89013. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  89014. for (var i = 0; i < 2; i++) {
  89015. for (var j = 0; j < 2; j++) {
  89016. var _loop_2 = function () {
  89017. var box = BABYLON.MeshBuilder.CreateBox("", { size: 0.1 }, gizmoLayer.utilityLayerScene);
  89018. box.material = coloredMaterial;
  89019. // Dragging logic
  89020. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  89021. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89022. _dragBehavior.moveAttached = false;
  89023. box.addBehavior(_dragBehavior);
  89024. _dragBehavior.onDragObservable.add(function (event) {
  89025. if (_this.attachedMesh) {
  89026. // Current boudning box dimensions
  89027. var boundingInfo = _this.attachedMesh.getBoundingInfo().boundingBox;
  89028. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(_this.attachedMesh.scaling);
  89029. // Get the change in bounding box size/2 and add this to the mesh's position to offset from scaling with center pivot point
  89030. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  89031. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  89032. var scaleRatio = deltaScale.divide(_this.attachedMesh.scaling).scaleInPlace(0.5);
  89033. var moveDirection = boundBoxDimensions.multiply(scaleRatio).multiplyInPlace(dragAxis);
  89034. var worldMoveDirection = BABYLON.Vector3.TransformCoordinates(moveDirection, _this.attachedMesh.getWorldMatrix().getRotationMatrix());
  89035. // Update scale and position
  89036. _this.attachedMesh.scaling.addInPlace(deltaScale);
  89037. _this.attachedMesh.getAbsolutePosition().addToRef(worldMoveDirection, _this._tmpVector);
  89038. _this.attachedMesh.setAbsolutePosition(_this._tmpVector);
  89039. }
  89040. });
  89041. // Selection/deselection
  89042. _dragBehavior.onDragStartObservable.add(function () {
  89043. _this._selectNode(box);
  89044. });
  89045. _dragBehavior.onDragEndObservable.add(function () {
  89046. _this._selectNode(null);
  89047. });
  89048. this_2._scaleBoxesParent.addChild(box);
  89049. };
  89050. var this_2 = this, _dragBehavior;
  89051. for (var k = 0; k < 2; k++) {
  89052. _loop_2();
  89053. }
  89054. }
  89055. }
  89056. _this._rootMesh.addChild(_this._scaleBoxesParent);
  89057. // Hover color change
  89058. var pointerIds = new Array();
  89059. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89060. if (!pointerIds[pointerInfo.event.pointerId]) {
  89061. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  89062. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  89063. pointerIds[pointerInfo.event.pointerId] = mesh;
  89064. mesh.material = hoverColoredMaterial;
  89065. }
  89066. });
  89067. }
  89068. else {
  89069. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  89070. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  89071. delete pointerIds[pointerInfo.event.pointerId];
  89072. }
  89073. }
  89074. });
  89075. // Update bounding box positions
  89076. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  89077. _this._updateBoundingBox();
  89078. });
  89079. _this._updateBoundingBox();
  89080. return _this;
  89081. }
  89082. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  89083. this._rotateSpheresParent.getChildMeshes()
  89084. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  89085. m.isVisible = (!selectedMesh || m == selectedMesh);
  89086. });
  89087. };
  89088. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  89089. if (this.attachedMesh) {
  89090. // Update bounding dimensions/positions
  89091. var boundingInfo = this.attachedMesh.getBoundingInfo().boundingBox;
  89092. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(this.attachedMesh.scaling);
  89093. this._boundingDimensions.copyFrom(boundBoxDimensions);
  89094. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  89095. }
  89096. // Update rotation sphere locations
  89097. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  89098. for (var i = 0; i < 3; i++) {
  89099. for (var j = 0; j < 2; j++) {
  89100. for (var k = 0; k < 2; k++) {
  89101. var index = ((i * 4) + (j * 2)) + k;
  89102. if (i == 0) {
  89103. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  89104. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89105. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89106. }
  89107. if (i == 1) {
  89108. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  89109. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89110. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89111. }
  89112. if (i == 2) {
  89113. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  89114. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89115. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89116. }
  89117. }
  89118. }
  89119. }
  89120. // Update scale box locations
  89121. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  89122. for (var i = 0; i < 2; i++) {
  89123. for (var j = 0; j < 2; j++) {
  89124. for (var k = 0; k < 2; k++) {
  89125. var index = ((i * 4) + (j * 2)) + k;
  89126. if (scaleBoxes[index]) {
  89127. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  89128. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89129. }
  89130. }
  89131. }
  89132. }
  89133. };
  89134. /**
  89135. * Disposes of the gizmo
  89136. */
  89137. BoundingBoxGizmo.prototype.dispose = function () {
  89138. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89139. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  89140. this._lineBoundingBox.dispose();
  89141. this._rotateSpheresParent.dispose();
  89142. this._scaleBoxesParent.dispose();
  89143. _super.prototype.dispose.call(this);
  89144. };
  89145. return BoundingBoxGizmo;
  89146. }(BABYLON.Gizmo));
  89147. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  89148. })(BABYLON || (BABYLON = {}));
  89149. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  89150. var BABYLON;
  89151. (function (BABYLON) {
  89152. /**
  89153. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  89154. */
  89155. var GizmoManager = /** @class */ (function () {
  89156. /**
  89157. * Instatiates a gizmo manager
  89158. * @param scene the scene to overlay the gizmos on top of
  89159. * @param options If only a single gizmo should exist at one time
  89160. */
  89161. function GizmoManager(scene, options) {
  89162. var _this = this;
  89163. this.scene = scene;
  89164. // Set of gizmos that are currently in the scene for each mesh
  89165. this._gizmoSet = {};
  89166. this._pointerObserver = null;
  89167. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  89168. // Options parsing
  89169. if (!options) {
  89170. options = {};
  89171. }
  89172. if (options.singleGizmo === undefined) {
  89173. options.singleGizmo = true;
  89174. }
  89175. // Instatiate/dispose gizmos based on pointer actions
  89176. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  89177. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89178. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  89179. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  89180. if (options.singleGizmo) {
  89181. _this._clearGizmos();
  89182. }
  89183. // Enable gizmo when mesh is selected
  89184. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  89185. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  89186. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  89187. }
  89188. else {
  89189. if (!options.singleGizmo) {
  89190. // Disable gizmo when clicked again
  89191. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  89192. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  89193. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  89194. }
  89195. }
  89196. }
  89197. else {
  89198. if (options.singleGizmo) {
  89199. // Disable gizmo when clicked away
  89200. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  89201. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  89202. if (gizmoPick && !gizmoPick.hit) {
  89203. _this._clearGizmos();
  89204. }
  89205. }
  89206. }
  89207. }
  89208. }
  89209. });
  89210. }
  89211. /**
  89212. * Disposes of the gizmo manager
  89213. */
  89214. GizmoManager.prototype.dispose = function () {
  89215. this.scene.onPointerObservable.remove(this._pointerObserver);
  89216. this._clearGizmos();
  89217. this._gizmoLayer.dispose();
  89218. };
  89219. GizmoManager.prototype._clearGizmos = function () {
  89220. for (var key in this._gizmoSet) {
  89221. if (this._gizmoSet.hasOwnProperty(key)) {
  89222. this._gizmoSet[key].positionGizmo.dispose();
  89223. this._gizmoSet[key].rotationGizmo.dispose();
  89224. delete this._gizmoSet[key];
  89225. }
  89226. }
  89227. };
  89228. return GizmoManager;
  89229. }());
  89230. BABYLON.GizmoManager = GizmoManager;
  89231. })(BABYLON || (BABYLON = {}));
  89232. //# sourceMappingURL=babylon.gizmoManager.js.map
  89233. var BABYLON;
  89234. (function (BABYLON) {
  89235. /**
  89236. * Defines a target to use with MorphTargetManager
  89237. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  89238. */
  89239. var MorphTarget = /** @class */ (function () {
  89240. /**
  89241. * Creates a new MorphTarget
  89242. * @param name defines the name of the target
  89243. * @param influence defines the influence to use
  89244. */
  89245. function MorphTarget(
  89246. /** defines the name of the target */
  89247. name, influence, scene) {
  89248. if (influence === void 0) { influence = 0; }
  89249. if (scene === void 0) { scene = null; }
  89250. this.name = name;
  89251. /**
  89252. * Gets or sets the list of animations
  89253. */
  89254. this.animations = new Array();
  89255. this._positions = null;
  89256. this._normals = null;
  89257. this._tangents = null;
  89258. /**
  89259. * Observable raised when the influence changes
  89260. */
  89261. this.onInfluenceChanged = new BABYLON.Observable();
  89262. this._animationPropertiesOverride = null;
  89263. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89264. this.influence = influence;
  89265. }
  89266. Object.defineProperty(MorphTarget.prototype, "influence", {
  89267. /**
  89268. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  89269. */
  89270. get: function () {
  89271. return this._influence;
  89272. },
  89273. set: function (influence) {
  89274. if (this._influence === influence) {
  89275. return;
  89276. }
  89277. var previous = this._influence;
  89278. this._influence = influence;
  89279. if (this.onInfluenceChanged.hasObservers) {
  89280. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  89281. }
  89282. },
  89283. enumerable: true,
  89284. configurable: true
  89285. });
  89286. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  89287. /**
  89288. * Gets or sets the animation properties override
  89289. */
  89290. get: function () {
  89291. if (!this._animationPropertiesOverride && this._scene) {
  89292. return this._scene.animationPropertiesOverride;
  89293. }
  89294. return this._animationPropertiesOverride;
  89295. },
  89296. set: function (value) {
  89297. this._animationPropertiesOverride = value;
  89298. },
  89299. enumerable: true,
  89300. configurable: true
  89301. });
  89302. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  89303. /**
  89304. * Gets a boolean defining if the target contains position data
  89305. */
  89306. get: function () {
  89307. return !!this._positions;
  89308. },
  89309. enumerable: true,
  89310. configurable: true
  89311. });
  89312. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  89313. /**
  89314. * Gets a boolean defining if the target contains normal data
  89315. */
  89316. get: function () {
  89317. return !!this._normals;
  89318. },
  89319. enumerable: true,
  89320. configurable: true
  89321. });
  89322. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  89323. /**
  89324. * Gets a boolean defining if the target contains tangent data
  89325. */
  89326. get: function () {
  89327. return !!this._tangents;
  89328. },
  89329. enumerable: true,
  89330. configurable: true
  89331. });
  89332. /**
  89333. * Affects position data to this target
  89334. * @param data defines the position data to use
  89335. */
  89336. MorphTarget.prototype.setPositions = function (data) {
  89337. this._positions = data;
  89338. };
  89339. /**
  89340. * Gets the position data stored in this target
  89341. * @returns a FloatArray containing the position data (or null if not present)
  89342. */
  89343. MorphTarget.prototype.getPositions = function () {
  89344. return this._positions;
  89345. };
  89346. /**
  89347. * Affects normal data to this target
  89348. * @param data defines the normal data to use
  89349. */
  89350. MorphTarget.prototype.setNormals = function (data) {
  89351. this._normals = data;
  89352. };
  89353. /**
  89354. * Gets the normal data stored in this target
  89355. * @returns a FloatArray containing the normal data (or null if not present)
  89356. */
  89357. MorphTarget.prototype.getNormals = function () {
  89358. return this._normals;
  89359. };
  89360. /**
  89361. * Affects tangent data to this target
  89362. * @param data defines the tangent data to use
  89363. */
  89364. MorphTarget.prototype.setTangents = function (data) {
  89365. this._tangents = data;
  89366. };
  89367. /**
  89368. * Gets the tangent data stored in this target
  89369. * @returns a FloatArray containing the tangent data (or null if not present)
  89370. */
  89371. MorphTarget.prototype.getTangents = function () {
  89372. return this._tangents;
  89373. };
  89374. /**
  89375. * Serializes the current target into a Serialization object
  89376. * @returns the serialized object
  89377. */
  89378. MorphTarget.prototype.serialize = function () {
  89379. var serializationObject = {};
  89380. serializationObject.name = this.name;
  89381. serializationObject.influence = this.influence;
  89382. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  89383. if (this.hasNormals) {
  89384. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  89385. }
  89386. if (this.hasTangents) {
  89387. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  89388. }
  89389. // Animations
  89390. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  89391. return serializationObject;
  89392. };
  89393. // Statics
  89394. /**
  89395. * Creates a new target from serialized data
  89396. * @param serializationObject defines the serialized data to use
  89397. * @returns a new MorphTarget
  89398. */
  89399. MorphTarget.Parse = function (serializationObject) {
  89400. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  89401. result.setPositions(serializationObject.positions);
  89402. if (serializationObject.normals) {
  89403. result.setNormals(serializationObject.normals);
  89404. }
  89405. if (serializationObject.tangents) {
  89406. result.setTangents(serializationObject.tangents);
  89407. }
  89408. // Animations
  89409. if (serializationObject.animations) {
  89410. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  89411. var parsedAnimation = serializationObject.animations[animationIndex];
  89412. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  89413. }
  89414. }
  89415. return result;
  89416. };
  89417. /**
  89418. * Creates a MorphTarget from mesh data
  89419. * @param mesh defines the source mesh
  89420. * @param name defines the name to use for the new target
  89421. * @param influence defines the influence to attach to the target
  89422. * @returns a new MorphTarget
  89423. */
  89424. MorphTarget.FromMesh = function (mesh, name, influence) {
  89425. if (!name) {
  89426. name = mesh.name;
  89427. }
  89428. var result = new MorphTarget(name, influence, mesh.getScene());
  89429. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  89430. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  89431. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  89432. }
  89433. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  89434. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  89435. }
  89436. return result;
  89437. };
  89438. return MorphTarget;
  89439. }());
  89440. BABYLON.MorphTarget = MorphTarget;
  89441. })(BABYLON || (BABYLON = {}));
  89442. //# sourceMappingURL=babylon.morphTarget.js.map
  89443. var BABYLON;
  89444. (function (BABYLON) {
  89445. /**
  89446. * This class is used to deform meshes using morphing between different targets
  89447. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  89448. */
  89449. var MorphTargetManager = /** @class */ (function () {
  89450. /**
  89451. * Creates a new MorphTargetManager
  89452. * @param scene defines the current scene
  89453. */
  89454. function MorphTargetManager(scene) {
  89455. if (scene === void 0) { scene = null; }
  89456. this._targets = new Array();
  89457. this._targetObservable = new Array();
  89458. this._activeTargets = new BABYLON.SmartArray(16);
  89459. this._supportsNormals = false;
  89460. this._supportsTangents = false;
  89461. this._vertexCount = 0;
  89462. this._uniqueId = 0;
  89463. this._tempInfluences = new Array();
  89464. if (!scene) {
  89465. scene = BABYLON.Engine.LastCreatedScene;
  89466. }
  89467. this._scene = scene;
  89468. if (this._scene) {
  89469. this._scene.morphTargetManagers.push(this);
  89470. this._uniqueId = this._scene.getUniqueId();
  89471. }
  89472. }
  89473. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  89474. /**
  89475. * Gets the unique ID of this manager
  89476. */
  89477. get: function () {
  89478. return this._uniqueId;
  89479. },
  89480. enumerable: true,
  89481. configurable: true
  89482. });
  89483. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  89484. /**
  89485. * Gets the number of vertices handled by this manager
  89486. */
  89487. get: function () {
  89488. return this._vertexCount;
  89489. },
  89490. enumerable: true,
  89491. configurable: true
  89492. });
  89493. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  89494. /**
  89495. * Gets a boolean indicating if this manager supports morphing of normals
  89496. */
  89497. get: function () {
  89498. return this._supportsNormals;
  89499. },
  89500. enumerable: true,
  89501. configurable: true
  89502. });
  89503. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  89504. /**
  89505. * Gets a boolean indicating if this manager supports morphing of tangents
  89506. */
  89507. get: function () {
  89508. return this._supportsTangents;
  89509. },
  89510. enumerable: true,
  89511. configurable: true
  89512. });
  89513. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  89514. /**
  89515. * Gets the number of targets stored in this manager
  89516. */
  89517. get: function () {
  89518. return this._targets.length;
  89519. },
  89520. enumerable: true,
  89521. configurable: true
  89522. });
  89523. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  89524. /**
  89525. * Gets the number of influencers (ie. the number of targets with influences > 0)
  89526. */
  89527. get: function () {
  89528. return this._activeTargets.length;
  89529. },
  89530. enumerable: true,
  89531. configurable: true
  89532. });
  89533. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  89534. /**
  89535. * Gets the list of influences (one per target)
  89536. */
  89537. get: function () {
  89538. return this._influences;
  89539. },
  89540. enumerable: true,
  89541. configurable: true
  89542. });
  89543. /**
  89544. * Gets the active target at specified index. An active target is a target with an influence > 0
  89545. * @param index defines the index to check
  89546. * @returns the requested target
  89547. */
  89548. MorphTargetManager.prototype.getActiveTarget = function (index) {
  89549. return this._activeTargets.data[index];
  89550. };
  89551. /**
  89552. * Gets the target at specified index
  89553. * @param index defines the index to check
  89554. * @returns the requested target
  89555. */
  89556. MorphTargetManager.prototype.getTarget = function (index) {
  89557. return this._targets[index];
  89558. };
  89559. /**
  89560. * Add a new target to this manager
  89561. * @param target defines the target to add
  89562. */
  89563. MorphTargetManager.prototype.addTarget = function (target) {
  89564. var _this = this;
  89565. this._targets.push(target);
  89566. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  89567. _this._syncActiveTargets(needUpdate);
  89568. }));
  89569. this._syncActiveTargets(true);
  89570. };
  89571. /**
  89572. * Removes a target from the manager
  89573. * @param target defines the target to remove
  89574. */
  89575. MorphTargetManager.prototype.removeTarget = function (target) {
  89576. var index = this._targets.indexOf(target);
  89577. if (index >= 0) {
  89578. this._targets.splice(index, 1);
  89579. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  89580. this._syncActiveTargets(true);
  89581. }
  89582. };
  89583. /**
  89584. * Serializes the current manager into a Serialization object
  89585. * @returns the serialized object
  89586. */
  89587. MorphTargetManager.prototype.serialize = function () {
  89588. var serializationObject = {};
  89589. serializationObject.id = this.uniqueId;
  89590. serializationObject.targets = [];
  89591. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  89592. var target = _a[_i];
  89593. serializationObject.targets.push(target.serialize());
  89594. }
  89595. return serializationObject;
  89596. };
  89597. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  89598. var influenceCount = 0;
  89599. this._activeTargets.reset();
  89600. this._supportsNormals = true;
  89601. this._supportsTangents = true;
  89602. this._vertexCount = 0;
  89603. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  89604. var target = _a[_i];
  89605. this._activeTargets.push(target);
  89606. this._tempInfluences[influenceCount++] = target.influence;
  89607. var positions = target.getPositions();
  89608. if (positions) {
  89609. this._supportsNormals = this._supportsNormals && target.hasNormals;
  89610. this._supportsTangents = this._supportsTangents && target.hasTangents;
  89611. var vertexCount = positions.length / 3;
  89612. if (this._vertexCount === 0) {
  89613. this._vertexCount = vertexCount;
  89614. }
  89615. else if (this._vertexCount !== vertexCount) {
  89616. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  89617. return;
  89618. }
  89619. }
  89620. }
  89621. if (!this._influences || this._influences.length !== influenceCount) {
  89622. this._influences = new Float32Array(influenceCount);
  89623. }
  89624. for (var index = 0; index < influenceCount; index++) {
  89625. this._influences[index] = this._tempInfluences[index];
  89626. }
  89627. if (needUpdate) {
  89628. this.synchronize();
  89629. }
  89630. };
  89631. /**
  89632. * Syncrhonize the targets with all the meshes using this morph target manager
  89633. */
  89634. MorphTargetManager.prototype.synchronize = function () {
  89635. if (!this._scene) {
  89636. return;
  89637. }
  89638. // Flag meshes as dirty to resync with the active targets
  89639. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  89640. var mesh = _a[_i];
  89641. if (mesh.morphTargetManager === this) {
  89642. mesh._syncGeometryWithMorphTargetManager();
  89643. }
  89644. }
  89645. };
  89646. // Statics
  89647. /**
  89648. * Creates a new MorphTargetManager from serialized data
  89649. * @param serializationObject defines the serialized data
  89650. * @param scene defines the hosting scene
  89651. * @returns the new MorphTargetManager
  89652. */
  89653. MorphTargetManager.Parse = function (serializationObject, scene) {
  89654. var result = new MorphTargetManager(scene);
  89655. result._uniqueId = serializationObject.id;
  89656. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  89657. var targetData = _a[_i];
  89658. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  89659. }
  89660. return result;
  89661. };
  89662. return MorphTargetManager;
  89663. }());
  89664. BABYLON.MorphTargetManager = MorphTargetManager;
  89665. })(BABYLON || (BABYLON = {}));
  89666. //# sourceMappingURL=babylon.morphTargetManager.js.map
  89667. var BABYLON;
  89668. (function (BABYLON) {
  89669. var Octree = /** @class */ (function () {
  89670. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  89671. if (maxDepth === void 0) { maxDepth = 2; }
  89672. this.maxDepth = maxDepth;
  89673. this.dynamicContent = new Array();
  89674. this._maxBlockCapacity = maxBlockCapacity || 64;
  89675. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  89676. this._creationFunc = creationFunc;
  89677. }
  89678. // Methods
  89679. Octree.prototype.update = function (worldMin, worldMax, entries) {
  89680. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  89681. };
  89682. Octree.prototype.addMesh = function (entry) {
  89683. for (var index = 0; index < this.blocks.length; index++) {
  89684. var block = this.blocks[index];
  89685. block.addEntry(entry);
  89686. }
  89687. };
  89688. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  89689. this._selectionContent.reset();
  89690. for (var index = 0; index < this.blocks.length; index++) {
  89691. var block = this.blocks[index];
  89692. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  89693. }
  89694. if (allowDuplicate) {
  89695. this._selectionContent.concat(this.dynamicContent);
  89696. }
  89697. else {
  89698. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  89699. }
  89700. return this._selectionContent;
  89701. };
  89702. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  89703. this._selectionContent.reset();
  89704. for (var index = 0; index < this.blocks.length; index++) {
  89705. var block = this.blocks[index];
  89706. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  89707. }
  89708. if (allowDuplicate) {
  89709. this._selectionContent.concat(this.dynamicContent);
  89710. }
  89711. else {
  89712. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  89713. }
  89714. return this._selectionContent;
  89715. };
  89716. Octree.prototype.intersectsRay = function (ray) {
  89717. this._selectionContent.reset();
  89718. for (var index = 0; index < this.blocks.length; index++) {
  89719. var block = this.blocks[index];
  89720. block.intersectsRay(ray, this._selectionContent);
  89721. }
  89722. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  89723. return this._selectionContent;
  89724. };
  89725. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  89726. target.blocks = new Array();
  89727. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  89728. // Segmenting space
  89729. for (var x = 0; x < 2; x++) {
  89730. for (var y = 0; y < 2; y++) {
  89731. for (var z = 0; z < 2; z++) {
  89732. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  89733. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  89734. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  89735. block.addEntries(entries);
  89736. target.blocks.push(block);
  89737. }
  89738. }
  89739. }
  89740. };
  89741. Octree.CreationFuncForMeshes = function (entry, block) {
  89742. var boundingInfo = entry.getBoundingInfo();
  89743. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  89744. block.entries.push(entry);
  89745. }
  89746. };
  89747. Octree.CreationFuncForSubMeshes = function (entry, block) {
  89748. var boundingInfo = entry.getBoundingInfo();
  89749. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  89750. block.entries.push(entry);
  89751. }
  89752. };
  89753. return Octree;
  89754. }());
  89755. BABYLON.Octree = Octree;
  89756. })(BABYLON || (BABYLON = {}));
  89757. //# sourceMappingURL=babylon.octree.js.map
  89758. var BABYLON;
  89759. (function (BABYLON) {
  89760. var OctreeBlock = /** @class */ (function () {
  89761. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  89762. this.entries = new Array();
  89763. this._boundingVectors = new Array();
  89764. this._capacity = capacity;
  89765. this._depth = depth;
  89766. this._maxDepth = maxDepth;
  89767. this._creationFunc = creationFunc;
  89768. this._minPoint = minPoint;
  89769. this._maxPoint = maxPoint;
  89770. this._boundingVectors.push(minPoint.clone());
  89771. this._boundingVectors.push(maxPoint.clone());
  89772. this._boundingVectors.push(minPoint.clone());
  89773. this._boundingVectors[2].x = maxPoint.x;
  89774. this._boundingVectors.push(minPoint.clone());
  89775. this._boundingVectors[3].y = maxPoint.y;
  89776. this._boundingVectors.push(minPoint.clone());
  89777. this._boundingVectors[4].z = maxPoint.z;
  89778. this._boundingVectors.push(maxPoint.clone());
  89779. this._boundingVectors[5].z = minPoint.z;
  89780. this._boundingVectors.push(maxPoint.clone());
  89781. this._boundingVectors[6].x = minPoint.x;
  89782. this._boundingVectors.push(maxPoint.clone());
  89783. this._boundingVectors[7].y = minPoint.y;
  89784. }
  89785. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  89786. // Property
  89787. get: function () {
  89788. return this._capacity;
  89789. },
  89790. enumerable: true,
  89791. configurable: true
  89792. });
  89793. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  89794. get: function () {
  89795. return this._minPoint;
  89796. },
  89797. enumerable: true,
  89798. configurable: true
  89799. });
  89800. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  89801. get: function () {
  89802. return this._maxPoint;
  89803. },
  89804. enumerable: true,
  89805. configurable: true
  89806. });
  89807. // Methods
  89808. OctreeBlock.prototype.addEntry = function (entry) {
  89809. if (this.blocks) {
  89810. for (var index = 0; index < this.blocks.length; index++) {
  89811. var block = this.blocks[index];
  89812. block.addEntry(entry);
  89813. }
  89814. return;
  89815. }
  89816. this._creationFunc(entry, this);
  89817. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  89818. this.createInnerBlocks();
  89819. }
  89820. };
  89821. OctreeBlock.prototype.addEntries = function (entries) {
  89822. for (var index = 0; index < entries.length; index++) {
  89823. var mesh = entries[index];
  89824. this.addEntry(mesh);
  89825. }
  89826. };
  89827. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  89828. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  89829. if (this.blocks) {
  89830. for (var index = 0; index < this.blocks.length; index++) {
  89831. var block = this.blocks[index];
  89832. block.select(frustumPlanes, selection, allowDuplicate);
  89833. }
  89834. return;
  89835. }
  89836. if (allowDuplicate) {
  89837. selection.concat(this.entries);
  89838. }
  89839. else {
  89840. selection.concatWithNoDuplicate(this.entries);
  89841. }
  89842. }
  89843. };
  89844. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  89845. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  89846. if (this.blocks) {
  89847. for (var index = 0; index < this.blocks.length; index++) {
  89848. var block = this.blocks[index];
  89849. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  89850. }
  89851. return;
  89852. }
  89853. if (allowDuplicate) {
  89854. selection.concat(this.entries);
  89855. }
  89856. else {
  89857. selection.concatWithNoDuplicate(this.entries);
  89858. }
  89859. }
  89860. };
  89861. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  89862. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  89863. if (this.blocks) {
  89864. for (var index = 0; index < this.blocks.length; index++) {
  89865. var block = this.blocks[index];
  89866. block.intersectsRay(ray, selection);
  89867. }
  89868. return;
  89869. }
  89870. selection.concatWithNoDuplicate(this.entries);
  89871. }
  89872. };
  89873. OctreeBlock.prototype.createInnerBlocks = function () {
  89874. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  89875. };
  89876. return OctreeBlock;
  89877. }());
  89878. BABYLON.OctreeBlock = OctreeBlock;
  89879. })(BABYLON || (BABYLON = {}));
  89880. //# sourceMappingURL=babylon.octreeBlock.js.map
  89881. var BABYLON;
  89882. (function (BABYLON) {
  89883. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  89884. __extends(VRDistortionCorrectionPostProcess, _super);
  89885. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  89886. var _this = _super.call(this, name, "vrDistortionCorrection", [
  89887. 'LensCenter',
  89888. 'Scale',
  89889. 'ScaleIn',
  89890. 'HmdWarpParam'
  89891. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  89892. _this._isRightEye = isRightEye;
  89893. _this._distortionFactors = vrMetrics.distortionK;
  89894. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  89895. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  89896. _this.adaptScaleToCurrentViewport = true;
  89897. _this.onSizeChangedObservable.add(function () {
  89898. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  89899. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  89900. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  89901. });
  89902. _this.onApplyObservable.add(function (effect) {
  89903. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  89904. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  89905. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  89906. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  89907. });
  89908. return _this;
  89909. }
  89910. return VRDistortionCorrectionPostProcess;
  89911. }(BABYLON.PostProcess));
  89912. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  89913. })(BABYLON || (BABYLON = {}));
  89914. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  89915. var BABYLON;
  89916. (function (BABYLON) {
  89917. /**
  89918. * Postprocess used to generate anaglyphic rendering
  89919. */
  89920. var AnaglyphPostProcess = /** @class */ (function (_super) {
  89921. __extends(AnaglyphPostProcess, _super);
  89922. /**
  89923. * Creates a new AnaglyphPostProcess
  89924. * @param name defines postprocess name
  89925. * @param options defines creation options or target ratio scale
  89926. * @param rigCameras defines cameras using this postprocess
  89927. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  89928. * @param engine defines hosting engine
  89929. * @param reusable defines if the postprocess will be reused multiple times per frame
  89930. */
  89931. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  89932. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  89933. _this._passedProcess = rigCameras[0]._rigPostProcess;
  89934. _this.onApplyObservable.add(function (effect) {
  89935. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  89936. });
  89937. return _this;
  89938. }
  89939. return AnaglyphPostProcess;
  89940. }(BABYLON.PostProcess));
  89941. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  89942. })(BABYLON || (BABYLON = {}));
  89943. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  89944. var BABYLON;
  89945. (function (BABYLON) {
  89946. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  89947. __extends(StereoscopicInterlacePostProcess, _super);
  89948. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  89949. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  89950. _this._passedProcess = rigCameras[0]._rigPostProcess;
  89951. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  89952. _this.onSizeChangedObservable.add(function () {
  89953. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  89954. });
  89955. _this.onApplyObservable.add(function (effect) {
  89956. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  89957. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  89958. });
  89959. return _this;
  89960. }
  89961. return StereoscopicInterlacePostProcess;
  89962. }(BABYLON.PostProcess));
  89963. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  89964. })(BABYLON || (BABYLON = {}));
  89965. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  89966. var BABYLON;
  89967. (function (BABYLON) {
  89968. /**
  89969. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  89970. * Screen rotation is taken into account.
  89971. */
  89972. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  89973. function FreeCameraDeviceOrientationInput() {
  89974. var _this = this;
  89975. this._screenOrientationAngle = 0;
  89976. this._screenQuaternion = new BABYLON.Quaternion();
  89977. this._alpha = 0;
  89978. this._beta = 0;
  89979. this._gamma = 0;
  89980. this._orientationChanged = function () {
  89981. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  89982. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  89983. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  89984. };
  89985. this._deviceOrientation = function (evt) {
  89986. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  89987. _this._beta = evt.beta !== null ? evt.beta : 0;
  89988. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  89989. };
  89990. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  89991. this._orientationChanged();
  89992. }
  89993. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  89994. get: function () {
  89995. return this._camera;
  89996. },
  89997. set: function (camera) {
  89998. this._camera = camera;
  89999. if (this._camera != null && !this._camera.rotationQuaternion) {
  90000. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  90001. }
  90002. },
  90003. enumerable: true,
  90004. configurable: true
  90005. });
  90006. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  90007. window.addEventListener("orientationchange", this._orientationChanged);
  90008. window.addEventListener("deviceorientation", this._deviceOrientation);
  90009. //In certain cases, the attach control is called AFTER orientation was changed,
  90010. //So this is needed.
  90011. this._orientationChanged();
  90012. };
  90013. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  90014. window.removeEventListener("orientationchange", this._orientationChanged);
  90015. window.removeEventListener("deviceorientation", this._deviceOrientation);
  90016. };
  90017. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  90018. //if no device orientation provided, don't update the rotation.
  90019. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  90020. if (!this._alpha)
  90021. return;
  90022. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  90023. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  90024. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  90025. //Mirror on XY Plane
  90026. this._camera.rotationQuaternion.z *= -1;
  90027. this._camera.rotationQuaternion.w *= -1;
  90028. };
  90029. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  90030. return "FreeCameraDeviceOrientationInput";
  90031. };
  90032. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  90033. return "deviceOrientation";
  90034. };
  90035. return FreeCameraDeviceOrientationInput;
  90036. }());
  90037. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  90038. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  90039. })(BABYLON || (BABYLON = {}));
  90040. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  90041. var BABYLON;
  90042. (function (BABYLON) {
  90043. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  90044. function ArcRotateCameraVRDeviceOrientationInput() {
  90045. this.alphaCorrection = 1;
  90046. this.betaCorrection = 1;
  90047. this.gammaCorrection = 1;
  90048. this._alpha = 0;
  90049. this._gamma = 0;
  90050. this._dirty = false;
  90051. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  90052. }
  90053. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  90054. this.camera.attachControl(element, noPreventDefault);
  90055. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  90056. };
  90057. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  90058. if (evt.alpha !== null) {
  90059. this._alpha = +evt.alpha | 0;
  90060. }
  90061. if (evt.gamma !== null) {
  90062. this._gamma = +evt.gamma | 0;
  90063. }
  90064. this._dirty = true;
  90065. };
  90066. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  90067. if (this._dirty) {
  90068. this._dirty = false;
  90069. if (this._gamma < 0) {
  90070. this._gamma = 180 + this._gamma;
  90071. }
  90072. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  90073. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  90074. }
  90075. };
  90076. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  90077. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  90078. };
  90079. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  90080. return "ArcRotateCameraVRDeviceOrientationInput";
  90081. };
  90082. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  90083. return "VRDeviceOrientation";
  90084. };
  90085. return ArcRotateCameraVRDeviceOrientationInput;
  90086. }());
  90087. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  90088. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  90089. })(BABYLON || (BABYLON = {}));
  90090. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  90091. var BABYLON;
  90092. (function (BABYLON) {
  90093. var VRCameraMetrics = /** @class */ (function () {
  90094. function VRCameraMetrics() {
  90095. this.compensateDistortion = true;
  90096. }
  90097. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  90098. get: function () {
  90099. return this.hResolution / (2 * this.vResolution);
  90100. },
  90101. enumerable: true,
  90102. configurable: true
  90103. });
  90104. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  90105. get: function () {
  90106. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  90107. },
  90108. enumerable: true,
  90109. configurable: true
  90110. });
  90111. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  90112. get: function () {
  90113. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  90114. var h = (4 * meters) / this.hScreenSize;
  90115. return BABYLON.Matrix.Translation(h, 0, 0);
  90116. },
  90117. enumerable: true,
  90118. configurable: true
  90119. });
  90120. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  90121. get: function () {
  90122. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  90123. var h = (4 * meters) / this.hScreenSize;
  90124. return BABYLON.Matrix.Translation(-h, 0, 0);
  90125. },
  90126. enumerable: true,
  90127. configurable: true
  90128. });
  90129. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  90130. get: function () {
  90131. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  90132. },
  90133. enumerable: true,
  90134. configurable: true
  90135. });
  90136. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  90137. get: function () {
  90138. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  90139. },
  90140. enumerable: true,
  90141. configurable: true
  90142. });
  90143. VRCameraMetrics.GetDefault = function () {
  90144. var result = new VRCameraMetrics();
  90145. result.hResolution = 1280;
  90146. result.vResolution = 800;
  90147. result.hScreenSize = 0.149759993;
  90148. result.vScreenSize = 0.0935999975;
  90149. result.vScreenCenter = 0.0467999987;
  90150. result.eyeToScreenDistance = 0.0410000011;
  90151. result.lensSeparationDistance = 0.0635000020;
  90152. result.interpupillaryDistance = 0.0640000030;
  90153. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  90154. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  90155. result.postProcessScaleFactor = 1.714605507808412;
  90156. result.lensCenterOffset = 0.151976421;
  90157. return result;
  90158. };
  90159. return VRCameraMetrics;
  90160. }());
  90161. BABYLON.VRCameraMetrics = VRCameraMetrics;
  90162. })(BABYLON || (BABYLON = {}));
  90163. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  90164. var BABYLON;
  90165. (function (BABYLON) {
  90166. /**
  90167. * This represents a WebVR camera.
  90168. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  90169. * @example http://doc.babylonjs.com/how_to/webvr_camera
  90170. */
  90171. var WebVRFreeCamera = /** @class */ (function (_super) {
  90172. __extends(WebVRFreeCamera, _super);
  90173. /**
  90174. * Instantiates a WebVRFreeCamera.
  90175. * @param name The name of the WebVRFreeCamera
  90176. * @param position The starting anchor position for the camera
  90177. * @param scene The scene the camera belongs to
  90178. * @param webVROptions a set of customizable options for the webVRCamera
  90179. */
  90180. function WebVRFreeCamera(name, position, scene, webVROptions) {
  90181. if (webVROptions === void 0) { webVROptions = {}; }
  90182. var _this = _super.call(this, name, position, scene) || this;
  90183. _this.webVROptions = webVROptions;
  90184. /**
  90185. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  90186. */
  90187. _this._vrDevice = null;
  90188. /**
  90189. * The rawPose of the vrDevice.
  90190. */
  90191. _this.rawPose = null;
  90192. _this._specsVersion = "1.1";
  90193. _this._attached = false;
  90194. _this._descendants = [];
  90195. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  90196. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  90197. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  90198. _this._standingMatrix = null;
  90199. /**
  90200. * Represents device position in babylon space.
  90201. */
  90202. _this.devicePosition = BABYLON.Vector3.Zero();
  90203. /**
  90204. * Represents device rotation in babylon space.
  90205. */
  90206. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  90207. /**
  90208. * The scale of the device to be used when translating from device space to babylon space.
  90209. */
  90210. _this.deviceScaleFactor = 1;
  90211. _this._deviceToWorld = BABYLON.Matrix.Identity();
  90212. _this._worldToDevice = BABYLON.Matrix.Identity();
  90213. /**
  90214. * References to the webVR controllers for the vrDevice.
  90215. */
  90216. _this.controllers = [];
  90217. /**
  90218. * Emits an event when a controller is attached.
  90219. */
  90220. _this.onControllersAttachedObservable = new BABYLON.Observable();
  90221. /**
  90222. * Emits an event when a controller's mesh has been loaded;
  90223. */
  90224. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  90225. /**
  90226. * If the rig cameras be used as parent instead of this camera.
  90227. */
  90228. _this.rigParenting = true;
  90229. _this._defaultHeight = undefined;
  90230. _this._workingVector = BABYLON.Vector3.Zero();
  90231. _this._oneVector = BABYLON.Vector3.One();
  90232. _this._workingMatrix = BABYLON.Matrix.Identity();
  90233. _this._cache.position = BABYLON.Vector3.Zero();
  90234. if (webVROptions.defaultHeight) {
  90235. _this._defaultHeight = webVROptions.defaultHeight;
  90236. _this.position.y = _this._defaultHeight;
  90237. }
  90238. _this.minZ = 0.1;
  90239. //legacy support - the compensation boolean was removed.
  90240. if (arguments.length === 5) {
  90241. _this.webVROptions = arguments[4];
  90242. }
  90243. // default webVR options
  90244. if (_this.webVROptions.trackPosition == undefined) {
  90245. _this.webVROptions.trackPosition = true;
  90246. }
  90247. if (_this.webVROptions.controllerMeshes == undefined) {
  90248. _this.webVROptions.controllerMeshes = true;
  90249. }
  90250. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  90251. _this.webVROptions.defaultLightingOnControllers = true;
  90252. }
  90253. _this.rotationQuaternion = new BABYLON.Quaternion();
  90254. if (_this.webVROptions && _this.webVROptions.positionScale) {
  90255. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  90256. }
  90257. //enable VR
  90258. var engine = _this.getEngine();
  90259. _this._onVREnabled = function (success) { if (success) {
  90260. _this.initControllers();
  90261. } };
  90262. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  90263. engine.initWebVR().add(function (event) {
  90264. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  90265. return;
  90266. }
  90267. _this._vrDevice = event.vrDisplay;
  90268. //reset the rig parameters.
  90269. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  90270. if (_this._attached) {
  90271. _this.getEngine().enableVR();
  90272. }
  90273. });
  90274. if (typeof (VRFrameData) !== "undefined")
  90275. _this._frameData = new VRFrameData();
  90276. /**
  90277. * The idea behind the following lines:
  90278. * objects that have the camera as parent should actually have the rig cameras as a parent.
  90279. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  90280. * the second will not show it correctly.
  90281. *
  90282. * To solve this - each object that has the camera as parent will be added to a protected array.
  90283. * When the rig camera renders, it will take this array and set all of those to be its children.
  90284. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  90285. * Amazing!
  90286. */
  90287. scene.onBeforeCameraRenderObservable.add(function (camera) {
  90288. if (camera.parent === _this && _this.rigParenting) {
  90289. _this._descendants = _this.getDescendants(true, function (n) {
  90290. // don't take the cameras or the controllers!
  90291. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  90292. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  90293. return !isController && !isRigCamera;
  90294. });
  90295. _this._descendants.forEach(function (node) {
  90296. node.parent = camera;
  90297. });
  90298. }
  90299. });
  90300. scene.onAfterCameraRenderObservable.add(function (camera) {
  90301. if (camera.parent === _this && _this.rigParenting) {
  90302. _this._descendants.forEach(function (node) {
  90303. node.parent = _this;
  90304. });
  90305. }
  90306. });
  90307. return _this;
  90308. }
  90309. /**
  90310. * Gets the device distance from the ground in meters.
  90311. * @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.
  90312. */
  90313. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  90314. if (this._standingMatrix) {
  90315. // Add standing matrix offset to get real offset from ground in room
  90316. this._standingMatrix.getTranslationToRef(this._workingVector);
  90317. return this._deviceRoomPosition.y + this._workingVector.y;
  90318. }
  90319. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  90320. return this._defaultHeight || 0;
  90321. };
  90322. /**
  90323. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  90324. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  90325. */
  90326. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  90327. var _this = this;
  90328. if (callback === void 0) { callback = function (bool) { }; }
  90329. // Use standing matrix if available
  90330. this.getEngine().initWebVRAsync().then(function (result) {
  90331. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  90332. callback(false);
  90333. }
  90334. else {
  90335. _this._standingMatrix = new BABYLON.Matrix();
  90336. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  90337. if (!_this.getScene().useRightHandedSystem) {
  90338. [2, 6, 8, 9, 14].forEach(function (num) {
  90339. if (_this._standingMatrix) {
  90340. _this._standingMatrix.m[num] *= -1;
  90341. }
  90342. });
  90343. }
  90344. callback(true);
  90345. }
  90346. });
  90347. };
  90348. /**
  90349. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  90350. * @returns A promise with a boolean set to if the standing matrix is supported.
  90351. */
  90352. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  90353. var _this = this;
  90354. return new Promise(function (res, rej) {
  90355. _this.useStandingMatrix(function (supported) {
  90356. res(supported);
  90357. });
  90358. });
  90359. };
  90360. /**
  90361. * Disposes the camera
  90362. */
  90363. WebVRFreeCamera.prototype.dispose = function () {
  90364. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  90365. _super.prototype.dispose.call(this);
  90366. };
  90367. /**
  90368. * Gets a vrController by name.
  90369. * @param name The name of the controller to retreive
  90370. * @returns the controller matching the name specified or null if not found
  90371. */
  90372. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  90373. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  90374. var gp = _a[_i];
  90375. if (gp.hand === name) {
  90376. return gp;
  90377. }
  90378. }
  90379. return null;
  90380. };
  90381. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  90382. /**
  90383. * The controller corrisponding to the users left hand.
  90384. */
  90385. get: function () {
  90386. if (!this._leftController) {
  90387. this._leftController = this.getControllerByName("left");
  90388. }
  90389. return this._leftController;
  90390. },
  90391. enumerable: true,
  90392. configurable: true
  90393. });
  90394. ;
  90395. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  90396. /**
  90397. * The controller corrisponding to the users right hand.
  90398. */
  90399. get: function () {
  90400. if (!this._rightController) {
  90401. this._rightController = this.getControllerByName("right");
  90402. }
  90403. return this._rightController;
  90404. },
  90405. enumerable: true,
  90406. configurable: true
  90407. });
  90408. ;
  90409. /**
  90410. * Casts a ray forward from the vrCamera's gaze.
  90411. * @param length Length of the ray (default: 100)
  90412. * @returns the ray corrisponding to the gaze
  90413. */
  90414. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  90415. if (length === void 0) { length = 100; }
  90416. if (this.leftCamera) {
  90417. // Use left eye to avoid computation to compute center on every call
  90418. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  90419. }
  90420. else {
  90421. return _super.prototype.getForwardRay.call(this, length);
  90422. }
  90423. };
  90424. /**
  90425. * Updates the camera based on device's frame data
  90426. */
  90427. WebVRFreeCamera.prototype._checkInputs = function () {
  90428. if (this._vrDevice && this._vrDevice.isPresenting) {
  90429. this._vrDevice.getFrameData(this._frameData);
  90430. this.updateFromDevice(this._frameData.pose);
  90431. }
  90432. _super.prototype._checkInputs.call(this);
  90433. };
  90434. /**
  90435. * Updates the poseControlled values based on the input device pose.
  90436. * @param poseData Pose coming from the device
  90437. */
  90438. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  90439. if (poseData && poseData.orientation) {
  90440. this.rawPose = poseData;
  90441. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  90442. if (this.getScene().useRightHandedSystem) {
  90443. this._deviceRoomRotationQuaternion.z *= -1;
  90444. this._deviceRoomRotationQuaternion.w *= -1;
  90445. }
  90446. if (this.webVROptions.trackPosition && this.rawPose.position) {
  90447. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  90448. if (this.getScene().useRightHandedSystem) {
  90449. this._deviceRoomPosition.z *= -1;
  90450. }
  90451. }
  90452. }
  90453. };
  90454. /**
  90455. * WebVR's attach control will start broadcasting frames to the device.
  90456. * Note that in certain browsers (chrome for example) this function must be called
  90457. * within a user-interaction callback. Example:
  90458. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  90459. *
  90460. * @param element html element to attach the vrDevice to
  90461. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  90462. */
  90463. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  90464. _super.prototype.attachControl.call(this, element, noPreventDefault);
  90465. this._attached = true;
  90466. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  90467. if (this._vrDevice) {
  90468. this.getEngine().enableVR();
  90469. }
  90470. };
  90471. /**
  90472. * Detaches the camera from the html element and disables VR
  90473. *
  90474. * @param element html element to detach from
  90475. */
  90476. WebVRFreeCamera.prototype.detachControl = function (element) {
  90477. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  90478. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  90479. _super.prototype.detachControl.call(this, element);
  90480. this._attached = false;
  90481. this.getEngine().disableVR();
  90482. };
  90483. /**
  90484. * @returns the name of this class
  90485. */
  90486. WebVRFreeCamera.prototype.getClassName = function () {
  90487. return "WebVRFreeCamera";
  90488. };
  90489. /**
  90490. * Calls resetPose on the vrDisplay
  90491. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  90492. */
  90493. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  90494. //uses the vrDisplay's "resetPose()".
  90495. //pitch and roll won't be affected.
  90496. this._vrDevice.resetPose();
  90497. };
  90498. /**
  90499. * Updates the rig cameras (left and right eye)
  90500. */
  90501. WebVRFreeCamera.prototype._updateRigCameras = function () {
  90502. var camLeft = this._rigCameras[0];
  90503. var camRight = this._rigCameras[1];
  90504. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  90505. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  90506. camLeft.position.copyFrom(this._deviceRoomPosition);
  90507. camRight.position.copyFrom(this._deviceRoomPosition);
  90508. };
  90509. /**
  90510. * Updates the cached values of the camera
  90511. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  90512. */
  90513. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  90514. var _this = this;
  90515. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  90516. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  90517. if (!this.updateCacheCalled) {
  90518. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  90519. this.updateCacheCalled = true;
  90520. this.update();
  90521. }
  90522. // Set working vector to the device position in room space rotated by the new rotation
  90523. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  90524. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  90525. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  90526. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  90527. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  90528. // Add translation from anchor position
  90529. this._deviceToWorld.getTranslationToRef(this._workingVector);
  90530. this._workingVector.addInPlace(this.position);
  90531. this._workingVector.subtractInPlace(this._cache.position);
  90532. this._deviceToWorld.setTranslation(this._workingVector);
  90533. // Set an inverted matrix to be used when updating the camera
  90534. this._deviceToWorld.invertToRef(this._worldToDevice);
  90535. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  90536. this.controllers.forEach(function (controller) {
  90537. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  90538. controller.update();
  90539. });
  90540. }
  90541. if (!ignoreParentClass) {
  90542. _super.prototype._updateCache.call(this);
  90543. }
  90544. this.updateCacheCalled = false;
  90545. };
  90546. /**
  90547. * Updates the current device position and rotation in the babylon world
  90548. */
  90549. WebVRFreeCamera.prototype.update = function () {
  90550. // Get current device position in babylon world
  90551. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  90552. // Get current device rotation in babylon world
  90553. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  90554. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  90555. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  90556. _super.prototype.update.call(this);
  90557. };
  90558. /**
  90559. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  90560. * @returns an identity matrix
  90561. */
  90562. WebVRFreeCamera.prototype._getViewMatrix = function () {
  90563. return BABYLON.Matrix.Identity();
  90564. };
  90565. /**
  90566. * This function is called by the two RIG cameras.
  90567. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  90568. */
  90569. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  90570. var _this = this;
  90571. // Update the parent camera prior to using a child camera to avoid desynchronization
  90572. var parentCamera = this._cameraRigParams["parentCamera"];
  90573. parentCamera._updateCache();
  90574. //WebVR 1.1
  90575. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  90576. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  90577. if (!this.getScene().useRightHandedSystem) {
  90578. [2, 6, 8, 9, 14].forEach(function (num) {
  90579. _this._webvrViewMatrix.m[num] *= -1;
  90580. });
  90581. }
  90582. // update the camera rotation matrix
  90583. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  90584. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  90585. // Computing target and final matrix
  90586. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  90587. // should the view matrix be updated with scale and position offset?
  90588. if (parentCamera.deviceScaleFactor !== 1) {
  90589. this._webvrViewMatrix.invert();
  90590. // scale the position, if set
  90591. if (parentCamera.deviceScaleFactor) {
  90592. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  90593. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  90594. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  90595. }
  90596. this._webvrViewMatrix.invert();
  90597. }
  90598. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  90599. // Compute global position
  90600. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  90601. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  90602. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  90603. this._workingMatrix.getTranslationToRef(this._globalPosition);
  90604. this._markSyncedWithParent();
  90605. return this._webvrViewMatrix;
  90606. };
  90607. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  90608. var _this = this;
  90609. var parentCamera = this.parent;
  90610. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  90611. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  90612. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  90613. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  90614. //babylon compatible matrix
  90615. if (!this.getScene().useRightHandedSystem) {
  90616. [8, 9, 10, 11].forEach(function (num) {
  90617. _this._projectionMatrix.m[num] *= -1;
  90618. });
  90619. }
  90620. return this._projectionMatrix;
  90621. };
  90622. /**
  90623. * Initializes the controllers and their meshes
  90624. */
  90625. WebVRFreeCamera.prototype.initControllers = function () {
  90626. var _this = this;
  90627. this.controllers = [];
  90628. var manager = this.getScene().gamepadManager;
  90629. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  90630. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  90631. var webVrController = gamepad;
  90632. if (webVrController.defaultModel) {
  90633. webVrController.defaultModel.setEnabled(false);
  90634. }
  90635. if (webVrController.hand === "right") {
  90636. _this._rightController = null;
  90637. }
  90638. if (webVrController.hand === "left") {
  90639. _this._leftController = null;
  90640. }
  90641. var controllerIndex = _this.controllers.indexOf(webVrController);
  90642. if (controllerIndex !== -1) {
  90643. _this.controllers.splice(controllerIndex, 1);
  90644. }
  90645. }
  90646. });
  90647. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  90648. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  90649. var webVrController_1 = gamepad;
  90650. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  90651. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  90652. if (_this.webVROptions.controllerMeshes) {
  90653. if (webVrController_1.defaultModel) {
  90654. webVrController_1.defaultModel.setEnabled(true);
  90655. }
  90656. else {
  90657. // Load the meshes
  90658. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  90659. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  90660. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  90661. if (_this.webVROptions.defaultLightingOnControllers) {
  90662. if (!_this._lightOnControllers) {
  90663. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  90664. }
  90665. var activateLightOnSubMeshes_1 = function (mesh, light) {
  90666. var children = mesh.getChildren();
  90667. if (children.length !== 0) {
  90668. children.forEach(function (mesh) {
  90669. light.includedOnlyMeshes.push(mesh);
  90670. activateLightOnSubMeshes_1(mesh, light);
  90671. });
  90672. }
  90673. };
  90674. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  90675. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  90676. }
  90677. });
  90678. }
  90679. }
  90680. webVrController_1.attachToPoseControlledCamera(_this);
  90681. // since this is async - sanity check. Is the controller already stored?
  90682. if (_this.controllers.indexOf(webVrController_1) === -1) {
  90683. //add to the controllers array
  90684. _this.controllers.push(webVrController_1);
  90685. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  90686. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  90687. // So we're overriding setting left & right manually to be sure
  90688. var firstViveWandDetected = false;
  90689. for (var i = 0; i < _this.controllers.length; i++) {
  90690. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  90691. if (!firstViveWandDetected) {
  90692. firstViveWandDetected = true;
  90693. _this.controllers[i].hand = "left";
  90694. }
  90695. else {
  90696. _this.controllers[i].hand = "right";
  90697. }
  90698. }
  90699. }
  90700. //did we find enough controllers? Great! let the developer know.
  90701. if (_this.controllers.length >= 2) {
  90702. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  90703. }
  90704. }
  90705. }
  90706. });
  90707. };
  90708. return WebVRFreeCamera;
  90709. }(BABYLON.FreeCamera));
  90710. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  90711. })(BABYLON || (BABYLON = {}));
  90712. //# sourceMappingURL=babylon.webVRCamera.js.map
  90713. var BABYLON;
  90714. (function (BABYLON) {
  90715. // We're mainly based on the logic defined into the FreeCamera code
  90716. /**
  90717. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  90718. * being tilted forward or back and left or right.
  90719. */
  90720. var DeviceOrientationCamera = /** @class */ (function (_super) {
  90721. __extends(DeviceOrientationCamera, _super);
  90722. /**
  90723. * Creates a new device orientation camera
  90724. * @param name The name of the camera
  90725. * @param position The start position camera
  90726. * @param scene The scene the camera belongs to
  90727. */
  90728. function DeviceOrientationCamera(name, position, scene) {
  90729. var _this = _super.call(this, name, position, scene) || this;
  90730. _this._quaternionCache = new BABYLON.Quaternion();
  90731. _this.inputs.addDeviceOrientation();
  90732. return _this;
  90733. }
  90734. /**
  90735. * Gets the current instance class name ("DeviceOrientationCamera").
  90736. * This helps avoiding instanceof at run time.
  90737. * @returns the class name
  90738. */
  90739. DeviceOrientationCamera.prototype.getClassName = function () {
  90740. return "DeviceOrientationCamera";
  90741. };
  90742. /**
  90743. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  90744. */
  90745. DeviceOrientationCamera.prototype._checkInputs = function () {
  90746. _super.prototype._checkInputs.call(this);
  90747. this._quaternionCache.copyFrom(this.rotationQuaternion);
  90748. if (this._initialQuaternion) {
  90749. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  90750. }
  90751. };
  90752. /**
  90753. * Reset the camera to its default orientation on the specified axis only.
  90754. * @param axis The axis to reset
  90755. */
  90756. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  90757. var _this = this;
  90758. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  90759. //can only work if this camera has a rotation quaternion already.
  90760. if (!this.rotationQuaternion)
  90761. return;
  90762. if (!this._initialQuaternion) {
  90763. this._initialQuaternion = new BABYLON.Quaternion();
  90764. }
  90765. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  90766. ['x', 'y', 'z'].forEach(function (axisName) {
  90767. if (!axis[axisName]) {
  90768. _this._initialQuaternion[axisName] = 0;
  90769. }
  90770. else {
  90771. _this._initialQuaternion[axisName] *= -1;
  90772. }
  90773. });
  90774. this._initialQuaternion.normalize();
  90775. //force rotation update
  90776. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  90777. };
  90778. return DeviceOrientationCamera;
  90779. }(BABYLON.FreeCamera));
  90780. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  90781. })(BABYLON || (BABYLON = {}));
  90782. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  90783. var BABYLON;
  90784. (function (BABYLON) {
  90785. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  90786. __extends(VRDeviceOrientationFreeCamera, _super);
  90787. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  90788. if (compensateDistortion === void 0) { compensateDistortion = true; }
  90789. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  90790. var _this = _super.call(this, name, position, scene) || this;
  90791. vrCameraMetrics.compensateDistortion = compensateDistortion;
  90792. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  90793. return _this;
  90794. }
  90795. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  90796. return "VRDeviceOrientationFreeCamera";
  90797. };
  90798. return VRDeviceOrientationFreeCamera;
  90799. }(BABYLON.DeviceOrientationCamera));
  90800. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  90801. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  90802. __extends(VRDeviceOrientationGamepadCamera, _super);
  90803. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  90804. if (compensateDistortion === void 0) { compensateDistortion = true; }
  90805. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  90806. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  90807. _this.inputs.addGamepad();
  90808. return _this;
  90809. }
  90810. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  90811. return "VRDeviceOrientationGamepadCamera";
  90812. };
  90813. return VRDeviceOrientationGamepadCamera;
  90814. }(VRDeviceOrientationFreeCamera));
  90815. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  90816. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  90817. __extends(VRDeviceOrientationArcRotateCamera, _super);
  90818. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  90819. if (compensateDistortion === void 0) { compensateDistortion = true; }
  90820. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  90821. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  90822. vrCameraMetrics.compensateDistortion = compensateDistortion;
  90823. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  90824. _this.inputs.addVRDeviceOrientation();
  90825. return _this;
  90826. }
  90827. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  90828. return "VRDeviceOrientationArcRotateCamera";
  90829. };
  90830. return VRDeviceOrientationArcRotateCamera;
  90831. }(BABYLON.ArcRotateCamera));
  90832. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  90833. })(BABYLON || (BABYLON = {}));
  90834. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  90835. var BABYLON;
  90836. (function (BABYLON) {
  90837. /**
  90838. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  90839. */
  90840. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  90841. __extends(AnaglyphFreeCamera, _super);
  90842. /**
  90843. * Creates a new AnaglyphFreeCamera
  90844. * @param name defines camera name
  90845. * @param position defines initial position
  90846. * @param interaxialDistance defines distance between each color axis
  90847. * @param scene defines the hosting scene
  90848. */
  90849. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  90850. var _this = _super.call(this, name, position, scene) || this;
  90851. _this.interaxialDistance = interaxialDistance;
  90852. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  90853. return _this;
  90854. }
  90855. /**
  90856. * Gets camera class name
  90857. * @returns AnaglyphFreeCamera
  90858. */
  90859. AnaglyphFreeCamera.prototype.getClassName = function () {
  90860. return "AnaglyphFreeCamera";
  90861. };
  90862. return AnaglyphFreeCamera;
  90863. }(BABYLON.FreeCamera));
  90864. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  90865. /**
  90866. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  90867. */
  90868. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  90869. __extends(AnaglyphArcRotateCamera, _super);
  90870. /**
  90871. * Creates a new AnaglyphArcRotateCamera
  90872. * @param name defines camera name
  90873. * @param alpha defines alpha angle (in radians)
  90874. * @param beta defines beta angle (in radians)
  90875. * @param radius defines radius
  90876. * @param target defines camera target
  90877. * @param interaxialDistance defines distance between each color axis
  90878. * @param scene defines the hosting scene
  90879. */
  90880. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  90881. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  90882. _this.interaxialDistance = interaxialDistance;
  90883. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  90884. return _this;
  90885. }
  90886. /**
  90887. * Gets camera class name
  90888. * @returns AnaglyphArcRotateCamera
  90889. */
  90890. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  90891. return "AnaglyphArcRotateCamera";
  90892. };
  90893. return AnaglyphArcRotateCamera;
  90894. }(BABYLON.ArcRotateCamera));
  90895. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  90896. /**
  90897. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  90898. */
  90899. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  90900. __extends(AnaglyphGamepadCamera, _super);
  90901. /**
  90902. * Creates a new AnaglyphGamepadCamera
  90903. * @param name defines camera name
  90904. * @param position defines initial position
  90905. * @param interaxialDistance defines distance between each color axis
  90906. * @param scene defines the hosting scene
  90907. */
  90908. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  90909. var _this = _super.call(this, name, position, scene) || this;
  90910. _this.interaxialDistance = interaxialDistance;
  90911. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  90912. return _this;
  90913. }
  90914. /**
  90915. * Gets camera class name
  90916. * @returns AnaglyphGamepadCamera
  90917. */
  90918. AnaglyphGamepadCamera.prototype.getClassName = function () {
  90919. return "AnaglyphGamepadCamera";
  90920. };
  90921. return AnaglyphGamepadCamera;
  90922. }(BABYLON.GamepadCamera));
  90923. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  90924. /**
  90925. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  90926. */
  90927. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  90928. __extends(AnaglyphUniversalCamera, _super);
  90929. /**
  90930. * Creates a new AnaglyphUniversalCamera
  90931. * @param name defines camera name
  90932. * @param position defines initial position
  90933. * @param interaxialDistance defines distance between each color axis
  90934. * @param scene defines the hosting scene
  90935. */
  90936. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  90937. var _this = _super.call(this, name, position, scene) || this;
  90938. _this.interaxialDistance = interaxialDistance;
  90939. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  90940. return _this;
  90941. }
  90942. /**
  90943. * Gets camera class name
  90944. * @returns AnaglyphUniversalCamera
  90945. */
  90946. AnaglyphUniversalCamera.prototype.getClassName = function () {
  90947. return "AnaglyphUniversalCamera";
  90948. };
  90949. return AnaglyphUniversalCamera;
  90950. }(BABYLON.UniversalCamera));
  90951. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  90952. /**
  90953. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  90954. */
  90955. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  90956. __extends(StereoscopicFreeCamera, _super);
  90957. /**
  90958. * Creates a new StereoscopicFreeCamera
  90959. * @param name defines camera name
  90960. * @param position defines initial position
  90961. * @param interaxialDistance defines distance between each color axis
  90962. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  90963. * @param scene defines the hosting scene
  90964. */
  90965. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  90966. var _this = _super.call(this, name, position, scene) || this;
  90967. _this.interaxialDistance = interaxialDistance;
  90968. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  90969. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  90970. return _this;
  90971. }
  90972. /**
  90973. * Gets camera class name
  90974. * @returns StereoscopicFreeCamera
  90975. */
  90976. StereoscopicFreeCamera.prototype.getClassName = function () {
  90977. return "StereoscopicFreeCamera";
  90978. };
  90979. return StereoscopicFreeCamera;
  90980. }(BABYLON.FreeCamera));
  90981. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  90982. /**
  90983. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  90984. */
  90985. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  90986. __extends(StereoscopicArcRotateCamera, _super);
  90987. /**
  90988. * Creates a new StereoscopicArcRotateCamera
  90989. * @param name defines camera name
  90990. * @param alpha defines alpha angle (in radians)
  90991. * @param beta defines beta angle (in radians)
  90992. * @param radius defines radius
  90993. * @param target defines camera target
  90994. * @param interaxialDistance defines distance between each color axis
  90995. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  90996. * @param scene defines the hosting scene
  90997. */
  90998. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  90999. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91000. _this.interaxialDistance = interaxialDistance;
  91001. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91002. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91003. return _this;
  91004. }
  91005. /**
  91006. * Gets camera class name
  91007. * @returns StereoscopicArcRotateCamera
  91008. */
  91009. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  91010. return "StereoscopicArcRotateCamera";
  91011. };
  91012. return StereoscopicArcRotateCamera;
  91013. }(BABYLON.ArcRotateCamera));
  91014. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  91015. /**
  91016. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  91017. */
  91018. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  91019. __extends(StereoscopicGamepadCamera, _super);
  91020. /**
  91021. * Creates a new StereoscopicGamepadCamera
  91022. * @param name defines camera name
  91023. * @param position defines initial position
  91024. * @param interaxialDistance defines distance between each color axis
  91025. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91026. * @param scene defines the hosting scene
  91027. */
  91028. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91029. var _this = _super.call(this, name, position, scene) || this;
  91030. _this.interaxialDistance = interaxialDistance;
  91031. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91032. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91033. return _this;
  91034. }
  91035. /**
  91036. * Gets camera class name
  91037. * @returns StereoscopicGamepadCamera
  91038. */
  91039. StereoscopicGamepadCamera.prototype.getClassName = function () {
  91040. return "StereoscopicGamepadCamera";
  91041. };
  91042. return StereoscopicGamepadCamera;
  91043. }(BABYLON.GamepadCamera));
  91044. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  91045. /**
  91046. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  91047. */
  91048. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  91049. __extends(StereoscopicUniversalCamera, _super);
  91050. /**
  91051. * Creates a new StereoscopicUniversalCamera
  91052. * @param name defines camera name
  91053. * @param position defines initial position
  91054. * @param interaxialDistance defines distance between each color axis
  91055. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91056. * @param scene defines the hosting scene
  91057. */
  91058. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91059. var _this = _super.call(this, name, position, scene) || this;
  91060. _this.interaxialDistance = interaxialDistance;
  91061. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91062. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91063. return _this;
  91064. }
  91065. /**
  91066. * Gets camera class name
  91067. * @returns StereoscopicUniversalCamera
  91068. */
  91069. StereoscopicUniversalCamera.prototype.getClassName = function () {
  91070. return "StereoscopicUniversalCamera";
  91071. };
  91072. return StereoscopicUniversalCamera;
  91073. }(BABYLON.UniversalCamera));
  91074. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  91075. })(BABYLON || (BABYLON = {}));
  91076. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  91077. var BABYLON;
  91078. (function (BABYLON) {
  91079. var VRExperienceHelperGazer = /** @class */ (function () {
  91080. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  91081. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  91082. this.scene = scene;
  91083. this._pointerDownOnMeshAsked = false;
  91084. this._isActionableMesh = false;
  91085. this._teleportationRequestInitiated = false;
  91086. this._teleportationBackRequestInitiated = false;
  91087. this._rotationRightAsked = false;
  91088. this._rotationLeftAsked = false;
  91089. this._dpadPressed = true;
  91090. this._activePointer = false;
  91091. this._id = VRExperienceHelperGazer._idCounter++;
  91092. // Gaze tracker
  91093. if (!gazeTrackerToClone) {
  91094. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  91095. this._gazeTracker.bakeCurrentTransformIntoVertices();
  91096. this._gazeTracker.isPickable = false;
  91097. this._gazeTracker.isVisible = false;
  91098. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  91099. targetMat.specularColor = BABYLON.Color3.Black();
  91100. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  91101. targetMat.backFaceCulling = false;
  91102. this._gazeTracker.material = targetMat;
  91103. }
  91104. else {
  91105. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  91106. }
  91107. }
  91108. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  91109. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  91110. };
  91111. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  91112. this._pointerDownOnMeshAsked = true;
  91113. if (this._currentHit) {
  91114. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  91115. }
  91116. };
  91117. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  91118. if (this._currentHit) {
  91119. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  91120. }
  91121. this._pointerDownOnMeshAsked = false;
  91122. };
  91123. VRExperienceHelperGazer.prototype._activatePointer = function () {
  91124. this._activePointer = true;
  91125. };
  91126. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  91127. this._activePointer = false;
  91128. };
  91129. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  91130. if (distance === void 0) { distance = 100; }
  91131. };
  91132. VRExperienceHelperGazer.prototype.dispose = function () {
  91133. this._interactionsEnabled = false;
  91134. this._teleportationEnabled = false;
  91135. if (this._gazeTracker) {
  91136. this._gazeTracker.dispose();
  91137. }
  91138. };
  91139. VRExperienceHelperGazer._idCounter = 0;
  91140. return VRExperienceHelperGazer;
  91141. }());
  91142. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  91143. __extends(VRExperienceHelperControllerGazer, _super);
  91144. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  91145. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  91146. _this.webVRController = webVRController;
  91147. // Laser pointer
  91148. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  91149. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  91150. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  91151. laserPointerMaterial.alpha = 0.6;
  91152. _this._laserPointer.material = laserPointerMaterial;
  91153. _this._laserPointer.rotation.x = Math.PI / 2;
  91154. _this._laserPointer.position.z = -0.5;
  91155. _this._laserPointer.isVisible = false;
  91156. _this._laserPointer.isPickable = false;
  91157. if (!webVRController.mesh) {
  91158. // Create an empty mesh that is used prior to loading the high quality model
  91159. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  91160. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  91161. preloadPointerPose.rotation.x = -0.7;
  91162. preloadMesh.addChild(preloadPointerPose);
  91163. webVRController.attachToMesh(preloadMesh);
  91164. }
  91165. _this._setLaserPointerParent(webVRController.mesh);
  91166. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  91167. _this._setLaserPointerParent(mesh);
  91168. });
  91169. return _this;
  91170. }
  91171. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  91172. return this.webVRController.getForwardRay(length);
  91173. };
  91174. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  91175. _super.prototype._activatePointer.call(this);
  91176. this._laserPointer.isVisible = true;
  91177. };
  91178. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  91179. _super.prototype._deactivatePointer.call(this);
  91180. this._laserPointer.isVisible = false;
  91181. };
  91182. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  91183. this._laserPointer.material.emissiveColor = color;
  91184. };
  91185. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  91186. var makeNotPick = function (root) {
  91187. root.name += " laserPointer";
  91188. root.isPickable = false;
  91189. root.getChildMeshes().forEach(function (c) {
  91190. makeNotPick(c);
  91191. });
  91192. };
  91193. makeNotPick(mesh);
  91194. var childMeshes = mesh.getChildMeshes();
  91195. this.webVRController._pointingPoseNode = null;
  91196. for (var i = 0; i < childMeshes.length; i++) {
  91197. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  91198. mesh = childMeshes[i];
  91199. this.webVRController._pointingPoseNode = mesh;
  91200. break;
  91201. }
  91202. }
  91203. this._laserPointer.parent = mesh;
  91204. };
  91205. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  91206. if (distance === void 0) { distance = 100; }
  91207. this._laserPointer.scaling.y = distance;
  91208. this._laserPointer.position.z = -distance / 2;
  91209. };
  91210. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  91211. _super.prototype.dispose.call(this);
  91212. this._laserPointer.dispose();
  91213. if (this._meshAttachedObserver) {
  91214. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  91215. }
  91216. };
  91217. return VRExperienceHelperControllerGazer;
  91218. }(VRExperienceHelperGazer));
  91219. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  91220. __extends(VRExperienceHelperCameraGazer, _super);
  91221. function VRExperienceHelperCameraGazer(getCamera, scene) {
  91222. var _this = _super.call(this, scene) || this;
  91223. _this.getCamera = getCamera;
  91224. return _this;
  91225. }
  91226. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  91227. var camera = this.getCamera();
  91228. if (camera) {
  91229. return camera.getForwardRay(length);
  91230. }
  91231. else {
  91232. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  91233. }
  91234. };
  91235. return VRExperienceHelperCameraGazer;
  91236. }(VRExperienceHelperGazer));
  91237. /**
  91238. * Helps to quickly add VR support to an existing scene.
  91239. * See http://doc.babylonjs.com/how_to/webvr_helper
  91240. */
  91241. var VRExperienceHelper = /** @class */ (function () {
  91242. /**
  91243. * Instantiates a VRExperienceHelper.
  91244. * Helps to quickly add VR support to an existing scene.
  91245. * @param scene The scene the VRExperienceHelper belongs to.
  91246. * @param webVROptions Options to modify the vr experience helper's behavior.
  91247. */
  91248. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  91249. if (webVROptions === void 0) { webVROptions = {}; }
  91250. var _this = this;
  91251. this.webVROptions = webVROptions;
  91252. // Can the system support WebVR, even if a headset isn't plugged in?
  91253. this._webVRsupported = false;
  91254. // If WebVR is supported, is a headset plugged in and are we ready to present?
  91255. this._webVRready = false;
  91256. // Are we waiting for the requestPresent callback to complete?
  91257. this._webVRrequesting = false;
  91258. // Are we presenting to the headset right now?
  91259. this._webVRpresenting = false;
  91260. // Are we presenting in the fullscreen fallback?
  91261. this._fullscreenVRpresenting = false;
  91262. /**
  91263. * Observable raised when entering VR.
  91264. */
  91265. this.onEnteringVRObservable = new BABYLON.Observable();
  91266. /**
  91267. * Observable raised when exiting VR.
  91268. */
  91269. this.onExitingVRObservable = new BABYLON.Observable();
  91270. /**
  91271. * Observable raised when controller mesh is loaded.
  91272. */
  91273. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  91274. this._useCustomVRButton = false;
  91275. this._teleportationRequested = false;
  91276. this._teleportActive = false;
  91277. this._floorMeshesCollection = [];
  91278. this._rotationAllowed = true;
  91279. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  91280. this._isDefaultTeleportationTarget = true;
  91281. this._teleportationFillColor = "#444444";
  91282. this._teleportationBorderColor = "#FFFFFF";
  91283. this._rotationAngle = 0;
  91284. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  91285. this._padSensibilityUp = 0.65;
  91286. this._padSensibilityDown = 0.35;
  91287. this.leftController = null;
  91288. this.rightController = null;
  91289. /**
  91290. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  91291. */
  91292. this.onNewMeshSelected = new BABYLON.Observable();
  91293. /**
  91294. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  91295. */
  91296. this.onNewMeshPicked = new BABYLON.Observable();
  91297. /**
  91298. * Observable raised before camera teleportation
  91299. */
  91300. this.onBeforeCameraTeleport = new BABYLON.Observable();
  91301. /**
  91302. * Observable raised after camera teleportation
  91303. */
  91304. this.onAfterCameraTeleport = new BABYLON.Observable();
  91305. /**
  91306. * Observable raised when current selected mesh gets unselected
  91307. */
  91308. this.onSelectedMeshUnselected = new BABYLON.Observable();
  91309. /**
  91310. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  91311. */
  91312. this.teleportationEnabled = true;
  91313. this._teleportationInitialized = false;
  91314. this._interactionsEnabled = false;
  91315. this._interactionsRequested = false;
  91316. this._displayGaze = true;
  91317. this._displayLaserPointer = true;
  91318. this._onResize = function () {
  91319. _this.moveButtonToBottomRight();
  91320. if (_this._fullscreenVRpresenting && _this._webVRready) {
  91321. _this.exitVR();
  91322. }
  91323. };
  91324. this._onFullscreenChange = function () {
  91325. if (document.fullscreen !== undefined) {
  91326. _this._fullscreenVRpresenting = document.fullscreen;
  91327. }
  91328. else if (document.mozFullScreen !== undefined) {
  91329. _this._fullscreenVRpresenting = document.mozFullScreen;
  91330. }
  91331. else if (document.webkitIsFullScreen !== undefined) {
  91332. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  91333. }
  91334. else if (document.msIsFullScreen !== undefined) {
  91335. _this._fullscreenVRpresenting = document.msIsFullScreen;
  91336. }
  91337. else if (document.msFullscreenElement !== undefined) {
  91338. _this._fullscreenVRpresenting = document.msFullscreenElement;
  91339. }
  91340. if (!_this._fullscreenVRpresenting && _this._canvas) {
  91341. _this.exitVR();
  91342. if (!_this._useCustomVRButton) {
  91343. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  91344. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  91345. }
  91346. }
  91347. };
  91348. this.beforeRender = function () {
  91349. if (_this.leftController && _this.leftController._activePointer) {
  91350. _this._castRayAndSelectObject(_this.leftController);
  91351. }
  91352. if (_this.rightController && _this.rightController._activePointer) {
  91353. _this._castRayAndSelectObject(_this.rightController);
  91354. }
  91355. if (_this._noControllerIsActive) {
  91356. _this._castRayAndSelectObject(_this._cameraGazer);
  91357. }
  91358. else {
  91359. _this._cameraGazer._gazeTracker.isVisible = false;
  91360. }
  91361. };
  91362. this._onNewGamepadConnected = function (gamepad) {
  91363. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  91364. if (gamepad.leftStick) {
  91365. gamepad.onleftstickchanged(function (stickValues) {
  91366. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  91367. // Listening to classic/xbox gamepad only if no VR controller is active
  91368. if ((!_this.leftController && !_this.rightController) ||
  91369. ((_this.leftController && !_this.leftController._activePointer) &&
  91370. (_this.rightController && !_this.rightController._activePointer))) {
  91371. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  91372. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  91373. }
  91374. }
  91375. });
  91376. }
  91377. if (gamepad.rightStick) {
  91378. gamepad.onrightstickchanged(function (stickValues) {
  91379. if (_this._teleportationInitialized) {
  91380. _this._checkRotate(stickValues, _this._cameraGazer);
  91381. }
  91382. });
  91383. }
  91384. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  91385. gamepad.onbuttondown(function (buttonPressed) {
  91386. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  91387. _this._cameraGazer._selectionPointerDown();
  91388. }
  91389. });
  91390. gamepad.onbuttonup(function (buttonPressed) {
  91391. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  91392. _this._cameraGazer._selectionPointerUp();
  91393. }
  91394. });
  91395. }
  91396. }
  91397. else {
  91398. var webVRController = gamepad;
  91399. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  91400. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  91401. _this.rightController = controller;
  91402. }
  91403. else {
  91404. _this.leftController = controller;
  91405. }
  91406. _this._tryEnableInteractionOnController(controller);
  91407. }
  91408. };
  91409. // 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
  91410. this._tryEnableInteractionOnController = function (controller) {
  91411. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  91412. _this._enableInteractionOnController(controller);
  91413. }
  91414. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  91415. _this._enableTeleportationOnController(controller);
  91416. }
  91417. };
  91418. this._onNewGamepadDisconnected = function (gamepad) {
  91419. if (gamepad instanceof BABYLON.WebVRController) {
  91420. if (gamepad.hand === "left" && _this.leftController != null) {
  91421. _this.leftController.dispose();
  91422. _this.leftController = null;
  91423. }
  91424. if (gamepad.hand === "right" && _this.rightController != null) {
  91425. _this.rightController.dispose();
  91426. _this.rightController = null;
  91427. }
  91428. }
  91429. };
  91430. this._workingVector = BABYLON.Vector3.Zero();
  91431. this._workingQuaternion = BABYLON.Quaternion.Identity();
  91432. this._workingMatrix = BABYLON.Matrix.Identity();
  91433. this._scene = scene;
  91434. this._canvas = scene.getEngine().getRenderingCanvas();
  91435. // Parse options
  91436. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  91437. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  91438. }
  91439. if (webVROptions.createDeviceOrientationCamera === undefined) {
  91440. webVROptions.createDeviceOrientationCamera = true;
  91441. }
  91442. if (webVROptions.laserToggle === undefined) {
  91443. webVROptions.laserToggle = true;
  91444. }
  91445. if (webVROptions.defaultHeight === undefined) {
  91446. webVROptions.defaultHeight = 1.7;
  91447. }
  91448. if (webVROptions.useCustomVRButton) {
  91449. this._useCustomVRButton = true;
  91450. if (webVROptions.customVRButton) {
  91451. this._btnVR = webVROptions.customVRButton;
  91452. }
  91453. }
  91454. if (webVROptions.rayLength) {
  91455. this._rayLength = webVROptions.rayLength;
  91456. }
  91457. this._defaultHeight = webVROptions.defaultHeight;
  91458. if (webVROptions.positionScale) {
  91459. this._rayLength *= webVROptions.positionScale;
  91460. this._defaultHeight *= webVROptions.positionScale;
  91461. }
  91462. // Set position
  91463. if (this._scene.activeCamera) {
  91464. this._position = this._scene.activeCamera.position.clone();
  91465. }
  91466. else {
  91467. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  91468. }
  91469. // Set non-vr camera
  91470. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  91471. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  91472. // Copy data from existing camera
  91473. if (this._scene.activeCamera) {
  91474. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  91475. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  91476. // Set rotation from previous camera
  91477. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  91478. var targetCamera = this._scene.activeCamera;
  91479. if (targetCamera.rotationQuaternion) {
  91480. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  91481. }
  91482. else {
  91483. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  91484. }
  91485. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  91486. }
  91487. }
  91488. this._scene.activeCamera = this._deviceOrientationCamera;
  91489. if (this._canvas) {
  91490. this._scene.activeCamera.attachControl(this._canvas);
  91491. }
  91492. }
  91493. else {
  91494. this._existingCamera = this._scene.activeCamera;
  91495. }
  91496. // Create VR cameras
  91497. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  91498. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  91499. }
  91500. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  91501. this._webVRCamera.useStandingMatrix();
  91502. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  91503. // Create default button
  91504. if (!this._useCustomVRButton) {
  91505. this._btnVR = document.createElement("BUTTON");
  91506. this._btnVR.className = "babylonVRicon";
  91507. this._btnVR.id = "babylonVRiconbtn";
  91508. this._btnVR.title = "Click to switch to VR";
  91509. 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) }";
  91510. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  91511. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  91512. // css += ".babylonVRicon.vrdisplaysupported { }";
  91513. // css += ".babylonVRicon.vrdisplayready { }";
  91514. // css += ".babylonVRicon.vrdisplayrequesting { }";
  91515. var style = document.createElement('style');
  91516. style.appendChild(document.createTextNode(css));
  91517. document.getElementsByTagName('head')[0].appendChild(style);
  91518. this.moveButtonToBottomRight();
  91519. }
  91520. // VR button click event
  91521. if (this._btnVR) {
  91522. this._btnVR.addEventListener("click", function () {
  91523. if (!_this.isInVRMode) {
  91524. _this.enterVR();
  91525. }
  91526. else {
  91527. _this.exitVR();
  91528. }
  91529. });
  91530. }
  91531. // Window events
  91532. window.addEventListener("resize", this._onResize);
  91533. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  91534. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  91535. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  91536. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  91537. document.onmsfullscreenchange = this._onFullscreenChange;
  91538. // Display vr button when headset is connected
  91539. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  91540. this.displayVRButton();
  91541. }
  91542. else {
  91543. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  91544. if (e.vrDisplay) {
  91545. _this.displayVRButton();
  91546. }
  91547. });
  91548. }
  91549. // Exiting VR mode using 'ESC' key on desktop
  91550. this._onKeyDown = function (event) {
  91551. if (event.keyCode === 27 && _this.isInVRMode) {
  91552. _this.exitVR();
  91553. }
  91554. };
  91555. document.addEventListener("keydown", this._onKeyDown);
  91556. // Exiting VR mode double tapping the touch screen
  91557. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  91558. if (_this.isInVRMode) {
  91559. _this.exitVR();
  91560. if (_this._fullscreenVRpresenting) {
  91561. _this._scene.getEngine().switchFullscreen(true);
  91562. }
  91563. }
  91564. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  91565. // Listen for WebVR display changes
  91566. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  91567. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  91568. this._onVRRequestPresentStart = function () {
  91569. _this._webVRrequesting = true;
  91570. _this.updateButtonVisibility();
  91571. };
  91572. this._onVRRequestPresentComplete = function (success) {
  91573. _this._webVRrequesting = false;
  91574. _this.updateButtonVisibility();
  91575. };
  91576. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  91577. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  91578. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  91579. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91580. scene.onDisposeObservable.add(function () {
  91581. _this.dispose();
  91582. });
  91583. // Gamepad connection events
  91584. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  91585. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  91586. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  91587. this.updateButtonVisibility();
  91588. //create easing functions
  91589. this._circleEase = new BABYLON.CircleEase();
  91590. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  91591. if (this.webVROptions.floorMeshes) {
  91592. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  91593. }
  91594. }
  91595. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  91596. /** Return this.onEnteringVRObservable
  91597. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  91598. */
  91599. get: function () {
  91600. return this.onEnteringVRObservable;
  91601. },
  91602. enumerable: true,
  91603. configurable: true
  91604. });
  91605. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  91606. /** Return this.onExitingVRObservable
  91607. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  91608. */
  91609. get: function () {
  91610. return this.onExitingVRObservable;
  91611. },
  91612. enumerable: true,
  91613. configurable: true
  91614. });
  91615. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  91616. /** Return this.onControllerMeshLoadedObservable
  91617. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  91618. */
  91619. get: function () {
  91620. return this.onControllerMeshLoadedObservable;
  91621. },
  91622. enumerable: true,
  91623. configurable: true
  91624. });
  91625. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  91626. /**
  91627. * The mesh used to display where the user is going to teleport.
  91628. */
  91629. get: function () {
  91630. return this._teleportationTarget;
  91631. },
  91632. /**
  91633. * Sets the mesh to be used to display where the user is going to teleport.
  91634. */
  91635. set: function (value) {
  91636. if (value) {
  91637. value.name = "teleportationTarget";
  91638. this._isDefaultTeleportationTarget = false;
  91639. this._teleportationTarget = value;
  91640. }
  91641. },
  91642. enumerable: true,
  91643. configurable: true
  91644. });
  91645. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  91646. /**
  91647. * The mesh used to display where the user is selecting,
  91648. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  91649. * See http://doc.babylonjs.com/resources/baking_transformations
  91650. */
  91651. get: function () {
  91652. return this._cameraGazer._gazeTracker;
  91653. },
  91654. set: function (value) {
  91655. if (value) {
  91656. this._cameraGazer._gazeTracker = value;
  91657. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  91658. this._cameraGazer._gazeTracker.isPickable = false;
  91659. this._cameraGazer._gazeTracker.isVisible = false;
  91660. this._cameraGazer._gazeTracker.name = "gazeTracker";
  91661. if (this.leftController) {
  91662. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  91663. }
  91664. if (this.rightController) {
  91665. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  91666. }
  91667. }
  91668. },
  91669. enumerable: true,
  91670. configurable: true
  91671. });
  91672. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  91673. /**
  91674. * If the ray of the gaze should be displayed.
  91675. */
  91676. get: function () {
  91677. return this._displayGaze;
  91678. },
  91679. /**
  91680. * Sets if the ray of the gaze should be displayed.
  91681. */
  91682. set: function (value) {
  91683. this._displayGaze = value;
  91684. if (!value) {
  91685. this._cameraGazer._gazeTracker.isVisible = false;
  91686. if (this.leftController) {
  91687. this.leftController._gazeTracker.isVisible = false;
  91688. }
  91689. if (this.rightController) {
  91690. this.rightController._gazeTracker.isVisible = false;
  91691. }
  91692. }
  91693. },
  91694. enumerable: true,
  91695. configurable: true
  91696. });
  91697. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  91698. /**
  91699. * If the ray of the LaserPointer should be displayed.
  91700. */
  91701. get: function () {
  91702. return this._displayLaserPointer;
  91703. },
  91704. /**
  91705. * Sets if the ray of the LaserPointer should be displayed.
  91706. */
  91707. set: function (value) {
  91708. this._displayLaserPointer = value;
  91709. if (!value) {
  91710. if (this.rightController) {
  91711. this.rightController._deactivatePointer();
  91712. this.rightController._gazeTracker.isVisible = false;
  91713. }
  91714. if (this.leftController) {
  91715. this.leftController._deactivatePointer();
  91716. this.leftController._gazeTracker.isVisible = false;
  91717. }
  91718. }
  91719. else {
  91720. if (this.rightController) {
  91721. this.rightController._activatePointer();
  91722. }
  91723. if (this.leftController) {
  91724. this.leftController._activatePointer();
  91725. }
  91726. }
  91727. },
  91728. enumerable: true,
  91729. configurable: true
  91730. });
  91731. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  91732. /**
  91733. * The deviceOrientationCamera used as the camera when not in VR.
  91734. */
  91735. get: function () {
  91736. return this._deviceOrientationCamera;
  91737. },
  91738. enumerable: true,
  91739. configurable: true
  91740. });
  91741. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  91742. /**
  91743. * Based on the current WebVR support, returns the current VR camera used.
  91744. */
  91745. get: function () {
  91746. if (this._webVRready) {
  91747. return this._webVRCamera;
  91748. }
  91749. else {
  91750. return this._scene.activeCamera;
  91751. }
  91752. },
  91753. enumerable: true,
  91754. configurable: true
  91755. });
  91756. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  91757. /**
  91758. * The webVRCamera which is used when in VR.
  91759. */
  91760. get: function () {
  91761. return this._webVRCamera;
  91762. },
  91763. enumerable: true,
  91764. configurable: true
  91765. });
  91766. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  91767. /**
  91768. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  91769. */
  91770. get: function () {
  91771. return this._vrDeviceOrientationCamera;
  91772. },
  91773. enumerable: true,
  91774. configurable: true
  91775. });
  91776. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  91777. get: function () {
  91778. var result = this._cameraGazer._teleportationRequestInitiated
  91779. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  91780. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  91781. return result;
  91782. },
  91783. enumerable: true,
  91784. configurable: true
  91785. });
  91786. // Raised when one of the controller has loaded successfully its associated default mesh
  91787. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  91788. if (this.leftController && this.leftController.webVRController == webVRController) {
  91789. if (webVRController.mesh) {
  91790. this.leftController._setLaserPointerParent(webVRController.mesh);
  91791. }
  91792. }
  91793. if (this.rightController && this.rightController.webVRController == webVRController) {
  91794. if (webVRController.mesh) {
  91795. this.rightController._setLaserPointerParent(webVRController.mesh);
  91796. }
  91797. }
  91798. try {
  91799. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  91800. }
  91801. catch (err) {
  91802. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  91803. }
  91804. };
  91805. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  91806. /**
  91807. * Gets a value indicating if we are currently in VR mode.
  91808. */
  91809. get: function () {
  91810. return this._webVRpresenting || this._fullscreenVRpresenting;
  91811. },
  91812. enumerable: true,
  91813. configurable: true
  91814. });
  91815. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  91816. var vrDisplay = this._scene.getEngine().getVRDevice();
  91817. if (vrDisplay) {
  91818. var wasPresenting = this._webVRpresenting;
  91819. // A VR display is connected
  91820. this._webVRpresenting = vrDisplay.isPresenting;
  91821. if (wasPresenting && !this._webVRpresenting)
  91822. this.exitVR();
  91823. }
  91824. else {
  91825. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  91826. }
  91827. this.updateButtonVisibility();
  91828. };
  91829. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  91830. this._webVRsupported = eventArgs.vrSupported;
  91831. this._webVRready = !!eventArgs.vrDisplay;
  91832. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  91833. this.updateButtonVisibility();
  91834. };
  91835. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  91836. if (this._canvas && !this._useCustomVRButton) {
  91837. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  91838. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  91839. }
  91840. };
  91841. VRExperienceHelper.prototype.displayVRButton = function () {
  91842. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  91843. document.body.appendChild(this._btnVR);
  91844. this._btnVRDisplayed = true;
  91845. }
  91846. };
  91847. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  91848. if (!this._btnVR || this._useCustomVRButton) {
  91849. return;
  91850. }
  91851. this._btnVR.className = "babylonVRicon";
  91852. if (this.isInVRMode) {
  91853. this._btnVR.className += " vrdisplaypresenting";
  91854. }
  91855. else {
  91856. if (this._webVRready)
  91857. this._btnVR.className += " vrdisplayready";
  91858. if (this._webVRsupported)
  91859. this._btnVR.className += " vrdisplaysupported";
  91860. if (this._webVRrequesting)
  91861. this._btnVR.className += " vrdisplayrequesting";
  91862. }
  91863. };
  91864. /**
  91865. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  91866. * Otherwise, will use the fullscreen API.
  91867. */
  91868. VRExperienceHelper.prototype.enterVR = function () {
  91869. if (this.onEnteringVRObservable) {
  91870. try {
  91871. this.onEnteringVRObservable.notifyObservers(this);
  91872. }
  91873. catch (err) {
  91874. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  91875. }
  91876. }
  91877. if (this._scene.activeCamera) {
  91878. this._position = this._scene.activeCamera.position.clone();
  91879. // make sure that we return to the last active camera
  91880. this._existingCamera = this._scene.activeCamera;
  91881. }
  91882. if (this._webVRrequesting)
  91883. return;
  91884. // If WebVR is supported and a headset is connected
  91885. if (this._webVRready) {
  91886. if (!this._webVRpresenting) {
  91887. this._webVRCamera.position = this._position;
  91888. this._scene.activeCamera = this._webVRCamera;
  91889. }
  91890. }
  91891. else if (this._vrDeviceOrientationCamera) {
  91892. this._vrDeviceOrientationCamera.position = this._position;
  91893. if (this._scene.activeCamera) {
  91894. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  91895. }
  91896. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  91897. this._scene.getEngine().switchFullscreen(true);
  91898. this.updateButtonVisibility();
  91899. }
  91900. if (this._scene.activeCamera && this._canvas) {
  91901. this._scene.activeCamera.attachControl(this._canvas);
  91902. }
  91903. if (this._interactionsEnabled) {
  91904. this._scene.registerBeforeRender(this.beforeRender);
  91905. }
  91906. };
  91907. /**
  91908. * Attempt to exit VR, or fullscreen.
  91909. */
  91910. VRExperienceHelper.prototype.exitVR = function () {
  91911. if (this.onExitingVRObservable) {
  91912. try {
  91913. this.onExitingVRObservable.notifyObservers(this);
  91914. }
  91915. catch (err) {
  91916. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  91917. }
  91918. }
  91919. if (this._webVRpresenting) {
  91920. this._scene.getEngine().disableVR();
  91921. }
  91922. if (this._scene.activeCamera) {
  91923. this._position = this._scene.activeCamera.position.clone();
  91924. }
  91925. if (this._deviceOrientationCamera) {
  91926. this._deviceOrientationCamera.position = this._position;
  91927. this._scene.activeCamera = this._deviceOrientationCamera;
  91928. if (this._canvas) {
  91929. this._scene.activeCamera.attachControl(this._canvas);
  91930. }
  91931. }
  91932. else if (this._existingCamera) {
  91933. this._existingCamera.position = this._position;
  91934. this._scene.activeCamera = this._existingCamera;
  91935. }
  91936. this.updateButtonVisibility();
  91937. if (this._interactionsEnabled) {
  91938. this._scene.unregisterBeforeRender(this.beforeRender);
  91939. }
  91940. // resize to update width and height when exiting vr exits fullscreen
  91941. this._scene.getEngine().resize();
  91942. };
  91943. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  91944. /**
  91945. * The position of the vr experience helper.
  91946. */
  91947. get: function () {
  91948. return this._position;
  91949. },
  91950. /**
  91951. * Sets the position of the vr experience helper.
  91952. */
  91953. set: function (value) {
  91954. this._position = value;
  91955. if (this._scene.activeCamera) {
  91956. this._scene.activeCamera.position = value;
  91957. }
  91958. },
  91959. enumerable: true,
  91960. configurable: true
  91961. });
  91962. /**
  91963. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  91964. */
  91965. VRExperienceHelper.prototype.enableInteractions = function () {
  91966. var _this = this;
  91967. if (!this._interactionsEnabled) {
  91968. this._interactionsRequested = true;
  91969. if (this.leftController) {
  91970. this._enableInteractionOnController(this.leftController);
  91971. }
  91972. if (this.rightController) {
  91973. this._enableInteractionOnController(this.rightController);
  91974. }
  91975. this.raySelectionPredicate = function (mesh) {
  91976. return mesh.isVisible;
  91977. };
  91978. this.meshSelectionPredicate = function (mesh) {
  91979. return true;
  91980. };
  91981. this._raySelectionPredicate = function (mesh) {
  91982. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  91983. && mesh.name.indexOf("teleportationTarget") === -1
  91984. && mesh.name.indexOf("torusTeleportation") === -1
  91985. && mesh.name.indexOf("laserPointer") === -1)) {
  91986. return _this.raySelectionPredicate(mesh);
  91987. }
  91988. return false;
  91989. };
  91990. this._interactionsEnabled = true;
  91991. }
  91992. };
  91993. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  91994. get: function () {
  91995. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  91996. },
  91997. enumerable: true,
  91998. configurable: true
  91999. });
  92000. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  92001. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  92002. if (this._floorMeshesCollection[i].id === mesh.id) {
  92003. return true;
  92004. }
  92005. }
  92006. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  92007. return true;
  92008. }
  92009. return false;
  92010. };
  92011. /**
  92012. * Adds a floor mesh to be used for teleportation.
  92013. * @param floorMesh the mesh to be used for teleportation.
  92014. */
  92015. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  92016. if (!this._floorMeshesCollection) {
  92017. return;
  92018. }
  92019. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  92020. return;
  92021. }
  92022. this._floorMeshesCollection.push(floorMesh);
  92023. };
  92024. /**
  92025. * Removes a floor mesh from being used for teleportation.
  92026. * @param floorMesh the mesh to be removed.
  92027. */
  92028. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  92029. if (!this._floorMeshesCollection) {
  92030. return;
  92031. }
  92032. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  92033. if (meshIndex !== -1) {
  92034. this._floorMeshesCollection.splice(meshIndex, 1);
  92035. }
  92036. };
  92037. /**
  92038. * Enables interactions and teleportation using the VR controllers and gaze.
  92039. * @param vrTeleportationOptions options to modify teleportation behavior.
  92040. */
  92041. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  92042. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  92043. if (!this._teleportationInitialized) {
  92044. this._teleportationRequested = true;
  92045. this.enableInteractions();
  92046. if (vrTeleportationOptions.floorMeshName) {
  92047. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  92048. }
  92049. if (vrTeleportationOptions.floorMeshes) {
  92050. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  92051. }
  92052. if (this.leftController != null) {
  92053. this._enableTeleportationOnController(this.leftController);
  92054. }
  92055. if (this.rightController != null) {
  92056. this._enableTeleportationOnController(this.rightController);
  92057. }
  92058. // Creates an image processing post process for the vignette not relying
  92059. // on the main scene configuration for image processing to reduce setup and spaces
  92060. // (gamma/linear) conflicts.
  92061. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  92062. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  92063. imageProcessingConfiguration.vignetteEnabled = true;
  92064. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  92065. this._webVRCamera.detachPostProcess(this._postProcessMove);
  92066. this._teleportationInitialized = true;
  92067. if (this._isDefaultTeleportationTarget) {
  92068. this._createTeleportationCircles();
  92069. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  92070. }
  92071. }
  92072. };
  92073. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  92074. var _this = this;
  92075. var controllerMesh = controller.webVRController.mesh;
  92076. if (controllerMesh) {
  92077. controller._interactionsEnabled = true;
  92078. controller._activatePointer();
  92079. if (this.webVROptions.laserToggle) {
  92080. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  92081. // Enabling / disabling laserPointer
  92082. if (_this._displayLaserPointer && stateObject.value === 1) {
  92083. if (controller._activePointer) {
  92084. controller._deactivatePointer();
  92085. }
  92086. else {
  92087. controller._activatePointer();
  92088. }
  92089. if (_this.displayGaze) {
  92090. controller._gazeTracker.isVisible = controller._activePointer;
  92091. }
  92092. }
  92093. });
  92094. }
  92095. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  92096. var gazer = controller;
  92097. if (_this._noControllerIsActive) {
  92098. gazer = _this._cameraGazer;
  92099. }
  92100. if (!gazer._pointerDownOnMeshAsked) {
  92101. if (stateObject.value > _this._padSensibilityUp) {
  92102. gazer._selectionPointerDown();
  92103. }
  92104. }
  92105. else if (stateObject.value < _this._padSensibilityDown) {
  92106. gazer._selectionPointerUp();
  92107. }
  92108. });
  92109. }
  92110. };
  92111. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  92112. // Dont teleport if another gaze already requested teleportation
  92113. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  92114. return;
  92115. }
  92116. if (!gazer._teleportationRequestInitiated) {
  92117. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  92118. gazer._activatePointer();
  92119. gazer._teleportationRequestInitiated = true;
  92120. }
  92121. }
  92122. else {
  92123. // Listening to the proper controller values changes to confirm teleportation
  92124. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  92125. if (this._teleportActive) {
  92126. this._teleportCamera(this._haloCenter);
  92127. }
  92128. gazer._teleportationRequestInitiated = false;
  92129. }
  92130. }
  92131. };
  92132. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  92133. // Only rotate when user is not currently selecting a teleportation location
  92134. if (gazer._teleportationRequestInitiated) {
  92135. return;
  92136. }
  92137. if (!gazer._rotationLeftAsked) {
  92138. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  92139. gazer._rotationLeftAsked = true;
  92140. if (this._rotationAllowed) {
  92141. this._rotateCamera(false);
  92142. }
  92143. }
  92144. }
  92145. else {
  92146. if (stateObject.x > -this._padSensibilityDown) {
  92147. gazer._rotationLeftAsked = false;
  92148. }
  92149. }
  92150. if (!gazer._rotationRightAsked) {
  92151. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  92152. gazer._rotationRightAsked = true;
  92153. if (this._rotationAllowed) {
  92154. this._rotateCamera(true);
  92155. }
  92156. }
  92157. }
  92158. else {
  92159. if (stateObject.x < this._padSensibilityDown) {
  92160. gazer._rotationRightAsked = false;
  92161. }
  92162. }
  92163. };
  92164. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  92165. // Only teleport backwards when user is not currently selecting a teleportation location
  92166. if (gazer._teleportationRequestInitiated) {
  92167. return;
  92168. }
  92169. // Teleport backwards
  92170. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  92171. if (!gazer._teleportationBackRequestInitiated) {
  92172. if (!this.currentVRCamera) {
  92173. return;
  92174. }
  92175. // Get rotation and position of the current camera
  92176. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  92177. var position = this.currentVRCamera.position;
  92178. // If the camera has device position, use that instead
  92179. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  92180. rotation = this.currentVRCamera.deviceRotationQuaternion;
  92181. position = this.currentVRCamera.devicePosition;
  92182. }
  92183. // Get matrix with only the y rotation of the device rotation
  92184. rotation.toEulerAnglesToRef(this._workingVector);
  92185. this._workingVector.z = 0;
  92186. this._workingVector.x = 0;
  92187. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  92188. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  92189. // Rotate backwards ray by device rotation to cast at the ground behind the user
  92190. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  92191. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  92192. var ray = new BABYLON.Ray(position, this._workingVector);
  92193. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  92194. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  92195. this._teleportCamera(hit.pickedPoint);
  92196. }
  92197. gazer._teleportationBackRequestInitiated = true;
  92198. }
  92199. }
  92200. else {
  92201. gazer._teleportationBackRequestInitiated = false;
  92202. }
  92203. };
  92204. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  92205. var _this = this;
  92206. var controllerMesh = controller.webVRController.mesh;
  92207. if (controllerMesh) {
  92208. if (!controller._interactionsEnabled) {
  92209. this._enableInteractionOnController(controller);
  92210. }
  92211. controller._interactionsEnabled = true;
  92212. controller._teleportationEnabled = true;
  92213. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  92214. controller._dpadPressed = false;
  92215. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  92216. controller._dpadPressed = stateObject.pressed;
  92217. if (!controller._dpadPressed) {
  92218. controller._rotationLeftAsked = false;
  92219. controller._rotationRightAsked = false;
  92220. controller._teleportationBackRequestInitiated = false;
  92221. }
  92222. });
  92223. }
  92224. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  92225. if (_this.teleportationEnabled) {
  92226. _this._checkTeleportBackwards(stateObject, controller);
  92227. _this._checkTeleportWithRay(stateObject, controller);
  92228. }
  92229. _this._checkRotate(stateObject, controller);
  92230. });
  92231. }
  92232. };
  92233. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  92234. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  92235. this._teleportationTarget.isPickable = false;
  92236. var length = 512;
  92237. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  92238. dynamicTexture.hasAlpha = true;
  92239. var context = dynamicTexture.getContext();
  92240. var centerX = length / 2;
  92241. var centerY = length / 2;
  92242. var radius = 200;
  92243. context.beginPath();
  92244. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  92245. context.fillStyle = this._teleportationFillColor;
  92246. context.fill();
  92247. context.lineWidth = 10;
  92248. context.strokeStyle = this._teleportationBorderColor;
  92249. context.stroke();
  92250. context.closePath();
  92251. dynamicTexture.update();
  92252. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  92253. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  92254. this._teleportationTarget.material = teleportationCircleMaterial;
  92255. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  92256. torus.isPickable = false;
  92257. torus.parent = this._teleportationTarget;
  92258. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  92259. var keys = [];
  92260. keys.push({
  92261. frame: 0,
  92262. value: 0
  92263. });
  92264. keys.push({
  92265. frame: 30,
  92266. value: 0.4
  92267. });
  92268. keys.push({
  92269. frame: 60,
  92270. value: 0
  92271. });
  92272. animationInnerCircle.setKeys(keys);
  92273. var easingFunction = new BABYLON.SineEase();
  92274. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  92275. animationInnerCircle.setEasingFunction(easingFunction);
  92276. torus.animations = [];
  92277. torus.animations.push(animationInnerCircle);
  92278. this._scene.beginAnimation(torus, 0, 60, true);
  92279. this._hideTeleportationTarget();
  92280. };
  92281. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  92282. this._teleportActive = true;
  92283. if (this._teleportationInitialized) {
  92284. this._teleportationTarget.isVisible = true;
  92285. if (this._isDefaultTeleportationTarget) {
  92286. this._teleportationTarget.getChildren()[0].isVisible = true;
  92287. }
  92288. }
  92289. };
  92290. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  92291. this._teleportActive = false;
  92292. if (this._teleportationInitialized) {
  92293. this._teleportationTarget.isVisible = false;
  92294. if (this._isDefaultTeleportationTarget) {
  92295. this._teleportationTarget.getChildren()[0].isVisible = false;
  92296. }
  92297. }
  92298. };
  92299. VRExperienceHelper.prototype._rotateCamera = function (right) {
  92300. var _this = this;
  92301. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  92302. return;
  92303. }
  92304. if (right) {
  92305. this._rotationAngle++;
  92306. }
  92307. else {
  92308. this._rotationAngle--;
  92309. }
  92310. this.currentVRCamera.animations = [];
  92311. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  92312. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92313. var animationRotationKeys = [];
  92314. animationRotationKeys.push({
  92315. frame: 0,
  92316. value: this.currentVRCamera.rotationQuaternion
  92317. });
  92318. animationRotationKeys.push({
  92319. frame: 6,
  92320. value: target
  92321. });
  92322. animationRotation.setKeys(animationRotationKeys);
  92323. animationRotation.setEasingFunction(this._circleEase);
  92324. this.currentVRCamera.animations.push(animationRotation);
  92325. this._postProcessMove.animations = [];
  92326. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92327. var vignetteWeightKeys = [];
  92328. vignetteWeightKeys.push({
  92329. frame: 0,
  92330. value: 0
  92331. });
  92332. vignetteWeightKeys.push({
  92333. frame: 3,
  92334. value: 4
  92335. });
  92336. vignetteWeightKeys.push({
  92337. frame: 6,
  92338. value: 0
  92339. });
  92340. animationPP.setKeys(vignetteWeightKeys);
  92341. animationPP.setEasingFunction(this._circleEase);
  92342. this._postProcessMove.animations.push(animationPP);
  92343. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92344. var vignetteStretchKeys = [];
  92345. vignetteStretchKeys.push({
  92346. frame: 0,
  92347. value: 0
  92348. });
  92349. vignetteStretchKeys.push({
  92350. frame: 3,
  92351. value: 10
  92352. });
  92353. vignetteStretchKeys.push({
  92354. frame: 6,
  92355. value: 0
  92356. });
  92357. animationPP2.setKeys(vignetteStretchKeys);
  92358. animationPP2.setEasingFunction(this._circleEase);
  92359. this._postProcessMove.animations.push(animationPP2);
  92360. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  92361. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  92362. this._postProcessMove.samples = 4;
  92363. this._webVRCamera.attachPostProcess(this._postProcessMove);
  92364. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  92365. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  92366. });
  92367. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  92368. };
  92369. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  92370. if (hit.pickedPoint) {
  92371. if (gazer._teleportationRequestInitiated) {
  92372. this._displayTeleportationTarget();
  92373. this._haloCenter.copyFrom(hit.pickedPoint);
  92374. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  92375. }
  92376. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  92377. if (pickNormal) {
  92378. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  92379. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  92380. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  92381. }
  92382. this._teleportationTarget.position.y += 0.1;
  92383. }
  92384. };
  92385. VRExperienceHelper.prototype._teleportCamera = function (location) {
  92386. var _this = this;
  92387. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  92388. return;
  92389. }
  92390. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  92391. // offset of the headset from the anchor.
  92392. if (this.webVRCamera.leftCamera) {
  92393. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  92394. this._workingVector.subtractInPlace(this.webVRCamera.position);
  92395. location.subtractToRef(this._workingVector, this._workingVector);
  92396. }
  92397. else {
  92398. this._workingVector.copyFrom(location);
  92399. }
  92400. // Add height to account for user's height offset
  92401. if (this.isInVRMode) {
  92402. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  92403. }
  92404. else {
  92405. this._workingVector.y += this._defaultHeight;
  92406. }
  92407. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  92408. // Create animation from the camera's position to the new location
  92409. this.currentVRCamera.animations = [];
  92410. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92411. var animationCameraTeleportationKeys = [{
  92412. frame: 0,
  92413. value: this.currentVRCamera.position
  92414. },
  92415. {
  92416. frame: 11,
  92417. value: this._workingVector
  92418. }
  92419. ];
  92420. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  92421. animationCameraTeleportation.setEasingFunction(this._circleEase);
  92422. this.currentVRCamera.animations.push(animationCameraTeleportation);
  92423. this._postProcessMove.animations = [];
  92424. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92425. var vignetteWeightKeys = [];
  92426. vignetteWeightKeys.push({
  92427. frame: 0,
  92428. value: 0
  92429. });
  92430. vignetteWeightKeys.push({
  92431. frame: 5,
  92432. value: 8
  92433. });
  92434. vignetteWeightKeys.push({
  92435. frame: 11,
  92436. value: 0
  92437. });
  92438. animationPP.setKeys(vignetteWeightKeys);
  92439. this._postProcessMove.animations.push(animationPP);
  92440. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92441. var vignetteStretchKeys = [];
  92442. vignetteStretchKeys.push({
  92443. frame: 0,
  92444. value: 0
  92445. });
  92446. vignetteStretchKeys.push({
  92447. frame: 5,
  92448. value: 10
  92449. });
  92450. vignetteStretchKeys.push({
  92451. frame: 11,
  92452. value: 0
  92453. });
  92454. animationPP2.setKeys(vignetteStretchKeys);
  92455. this._postProcessMove.animations.push(animationPP2);
  92456. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  92457. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  92458. this._webVRCamera.attachPostProcess(this._postProcessMove);
  92459. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  92460. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  92461. });
  92462. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  92463. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  92464. });
  92465. this._hideTeleportationTarget();
  92466. };
  92467. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  92468. if (normal) {
  92469. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  92470. if (angle < Math.PI / 2) {
  92471. normal.scaleInPlace(-1);
  92472. }
  92473. }
  92474. return normal;
  92475. };
  92476. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  92477. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  92478. return;
  92479. }
  92480. var ray = gazer._getForwardRay(this._rayLength);
  92481. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  92482. if (hit) {
  92483. // Populate the contrllers mesh that can be used for drag/drop
  92484. if (gazer._laserPointer) {
  92485. hit.originMesh = gazer._laserPointer.parent;
  92486. }
  92487. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  92488. }
  92489. gazer._currentHit = hit;
  92490. // Moving the gazeTracker on the mesh face targetted
  92491. if (hit && hit.pickedPoint) {
  92492. if (this._displayGaze) {
  92493. var multiplier = 1;
  92494. gazer._gazeTracker.isVisible = true;
  92495. if (gazer._isActionableMesh) {
  92496. multiplier = 3;
  92497. }
  92498. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  92499. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  92500. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  92501. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  92502. // To avoid z-fighting
  92503. var deltaFighting = 0.002;
  92504. if (pickNormal) {
  92505. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  92506. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  92507. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  92508. }
  92509. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  92510. if (gazer._gazeTracker.position.x < 0) {
  92511. gazer._gazeTracker.position.x += deltaFighting;
  92512. }
  92513. else {
  92514. gazer._gazeTracker.position.x -= deltaFighting;
  92515. }
  92516. if (gazer._gazeTracker.position.y < 0) {
  92517. gazer._gazeTracker.position.y += deltaFighting;
  92518. }
  92519. else {
  92520. gazer._gazeTracker.position.y -= deltaFighting;
  92521. }
  92522. if (gazer._gazeTracker.position.z < 0) {
  92523. gazer._gazeTracker.position.z += deltaFighting;
  92524. }
  92525. else {
  92526. gazer._gazeTracker.position.z -= deltaFighting;
  92527. }
  92528. }
  92529. // Changing the size of the laser pointer based on the distance from the targetted point
  92530. gazer._updatePointerDistance(hit.distance);
  92531. }
  92532. else {
  92533. gazer._updatePointerDistance();
  92534. gazer._gazeTracker.isVisible = false;
  92535. }
  92536. if (hit && hit.pickedMesh) {
  92537. // The object selected is the floor, we're in a teleportation scenario
  92538. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  92539. // Moving the teleportation area to this targetted point
  92540. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  92541. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  92542. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  92543. }
  92544. gazer._currentMeshSelected = null;
  92545. if (gazer._teleportationRequestInitiated) {
  92546. this._moveTeleportationSelectorTo(hit, gazer, ray);
  92547. }
  92548. return;
  92549. }
  92550. // If not, we're in a selection scenario
  92551. //this._teleportationAllowed = false;
  92552. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  92553. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  92554. this.onNewMeshPicked.notifyObservers(hit);
  92555. gazer._currentMeshSelected = hit.pickedMesh;
  92556. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  92557. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  92558. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  92559. gazer._isActionableMesh = true;
  92560. }
  92561. else {
  92562. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92563. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92564. gazer._isActionableMesh = false;
  92565. }
  92566. try {
  92567. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  92568. }
  92569. catch (err) {
  92570. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  92571. }
  92572. }
  92573. else {
  92574. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  92575. gazer._currentMeshSelected = null;
  92576. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92577. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92578. }
  92579. }
  92580. }
  92581. else {
  92582. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  92583. gazer._currentMeshSelected = null;
  92584. //this._teleportationAllowed = false;
  92585. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92586. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92587. }
  92588. };
  92589. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  92590. if (mesh) {
  92591. this.onSelectedMeshUnselected.notifyObservers(mesh);
  92592. }
  92593. };
  92594. /**
  92595. * Sets the color of the laser ray from the vr controllers.
  92596. * @param color new color for the ray.
  92597. */
  92598. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  92599. if (this.leftController) {
  92600. this.leftController._setLaserPointerColor(color);
  92601. }
  92602. if (this.rightController) {
  92603. this.rightController._setLaserPointerColor(color);
  92604. }
  92605. };
  92606. /**
  92607. * Sets the color of the ray from the vr headsets gaze.
  92608. * @param color new color for the ray.
  92609. */
  92610. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  92611. if (!this._cameraGazer._gazeTracker.material) {
  92612. return;
  92613. }
  92614. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  92615. if (this.leftController) {
  92616. this.leftController._gazeTracker.material.emissiveColor = color;
  92617. }
  92618. if (this.rightController) {
  92619. this.rightController._gazeTracker.material.emissiveColor = color;
  92620. }
  92621. };
  92622. /**
  92623. * Exits VR and disposes of the vr experience helper
  92624. */
  92625. VRExperienceHelper.prototype.dispose = function () {
  92626. if (this.isInVRMode) {
  92627. this.exitVR();
  92628. }
  92629. if (this._postProcessMove) {
  92630. this._postProcessMove.dispose();
  92631. }
  92632. if (this._webVRCamera) {
  92633. this._webVRCamera.dispose();
  92634. }
  92635. if (this._vrDeviceOrientationCamera) {
  92636. this._vrDeviceOrientationCamera.dispose();
  92637. }
  92638. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  92639. document.body.removeChild(this._btnVR);
  92640. }
  92641. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  92642. this._deviceOrientationCamera.dispose();
  92643. }
  92644. if (this._cameraGazer) {
  92645. this._cameraGazer.dispose();
  92646. }
  92647. if (this.leftController) {
  92648. this.leftController.dispose();
  92649. }
  92650. if (this.rightController) {
  92651. this.rightController.dispose();
  92652. }
  92653. if (this._teleportationTarget) {
  92654. this._teleportationTarget.dispose();
  92655. }
  92656. this._floorMeshesCollection = [];
  92657. document.removeEventListener("keydown", this._onKeyDown);
  92658. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92659. window.removeEventListener("resize", this._onResize);
  92660. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  92661. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  92662. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  92663. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  92664. document.onmsfullscreenchange = null;
  92665. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  92666. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  92667. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  92668. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92669. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  92670. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  92671. this._scene.unregisterBeforeRender(this.beforeRender);
  92672. };
  92673. /**
  92674. * Gets the name of the VRExperienceHelper class
  92675. * @returns "VRExperienceHelper"
  92676. */
  92677. VRExperienceHelper.prototype.getClassName = function () {
  92678. return "VRExperienceHelper";
  92679. };
  92680. return VRExperienceHelper;
  92681. }());
  92682. BABYLON.VRExperienceHelper = VRExperienceHelper;
  92683. })(BABYLON || (BABYLON = {}));
  92684. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  92685. // Mainly based on these 2 articles :
  92686. // 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
  92687. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  92688. var BABYLON;
  92689. (function (BABYLON) {
  92690. /**
  92691. * Defines the potential axis of a Joystick
  92692. */
  92693. var JoystickAxis;
  92694. (function (JoystickAxis) {
  92695. /** X axis */
  92696. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  92697. /** Y axis */
  92698. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  92699. /** Z axis */
  92700. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  92701. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  92702. /**
  92703. * Class used to define virtual joystick (used in touch mode)
  92704. */
  92705. var VirtualJoystick = /** @class */ (function () {
  92706. /**
  92707. * Creates a new virtual joystick
  92708. * @param leftJoystick defines that the joystick is for left hand (false by default)
  92709. */
  92710. function VirtualJoystick(leftJoystick) {
  92711. var _this = this;
  92712. if (leftJoystick) {
  92713. this._leftJoystick = true;
  92714. }
  92715. else {
  92716. this._leftJoystick = false;
  92717. }
  92718. VirtualJoystick._globalJoystickIndex++;
  92719. // By default left & right arrow keys are moving the X
  92720. // and up & down keys are moving the Y
  92721. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  92722. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  92723. this.reverseLeftRight = false;
  92724. this.reverseUpDown = false;
  92725. // collections of pointers
  92726. this._touches = new BABYLON.StringDictionary();
  92727. this.deltaPosition = BABYLON.Vector3.Zero();
  92728. this._joystickSensibility = 25;
  92729. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  92730. this._onResize = function (evt) {
  92731. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  92732. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  92733. if (VirtualJoystick.vjCanvas) {
  92734. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  92735. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  92736. }
  92737. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  92738. };
  92739. // injecting a canvas element on top of the canvas 3D game
  92740. if (!VirtualJoystick.vjCanvas) {
  92741. window.addEventListener("resize", this._onResize, false);
  92742. VirtualJoystick.vjCanvas = document.createElement("canvas");
  92743. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  92744. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  92745. VirtualJoystick.vjCanvas.width = window.innerWidth;
  92746. VirtualJoystick.vjCanvas.height = window.innerHeight;
  92747. VirtualJoystick.vjCanvas.style.width = "100%";
  92748. VirtualJoystick.vjCanvas.style.height = "100%";
  92749. VirtualJoystick.vjCanvas.style.position = "absolute";
  92750. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  92751. VirtualJoystick.vjCanvas.style.top = "0px";
  92752. VirtualJoystick.vjCanvas.style.left = "0px";
  92753. VirtualJoystick.vjCanvas.style.zIndex = "5";
  92754. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  92755. // Support for jQuery PEP polyfill
  92756. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  92757. var context = VirtualJoystick.vjCanvas.getContext('2d');
  92758. if (!context) {
  92759. throw new Error("Unable to create canvas for virtual joystick");
  92760. }
  92761. VirtualJoystick.vjCanvasContext = context;
  92762. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  92763. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  92764. document.body.appendChild(VirtualJoystick.vjCanvas);
  92765. }
  92766. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  92767. this.pressed = false;
  92768. // default joystick color
  92769. this._joystickColor = "cyan";
  92770. this._joystickPointerID = -1;
  92771. // current joystick position
  92772. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  92773. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  92774. // origin joystick position
  92775. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  92776. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  92777. this._onPointerDownHandlerRef = function (evt) {
  92778. _this._onPointerDown(evt);
  92779. };
  92780. this._onPointerMoveHandlerRef = function (evt) {
  92781. _this._onPointerMove(evt);
  92782. };
  92783. this._onPointerUpHandlerRef = function (evt) {
  92784. _this._onPointerUp(evt);
  92785. };
  92786. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  92787. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  92788. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  92789. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  92790. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  92791. evt.preventDefault(); // Disables system menu
  92792. }, false);
  92793. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  92794. }
  92795. /**
  92796. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  92797. * @param newJoystickSensibility defines the new sensibility
  92798. */
  92799. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  92800. this._joystickSensibility = newJoystickSensibility;
  92801. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  92802. };
  92803. VirtualJoystick.prototype._onPointerDown = function (e) {
  92804. var positionOnScreenCondition;
  92805. e.preventDefault();
  92806. if (this._leftJoystick === true) {
  92807. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  92808. }
  92809. else {
  92810. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  92811. }
  92812. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  92813. // First contact will be dedicated to the virtual joystick
  92814. this._joystickPointerID = e.pointerId;
  92815. this._joystickPointerStartPos.x = e.clientX;
  92816. this._joystickPointerStartPos.y = e.clientY;
  92817. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  92818. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  92819. this._deltaJoystickVector.x = 0;
  92820. this._deltaJoystickVector.y = 0;
  92821. this.pressed = true;
  92822. this._touches.add(e.pointerId.toString(), e);
  92823. }
  92824. else {
  92825. // You can only trigger the action buttons with a joystick declared
  92826. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  92827. this._action();
  92828. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  92829. }
  92830. }
  92831. };
  92832. VirtualJoystick.prototype._onPointerMove = function (e) {
  92833. // If the current pointer is the one associated to the joystick (first touch contact)
  92834. if (this._joystickPointerID == e.pointerId) {
  92835. this._joystickPointerPos.x = e.clientX;
  92836. this._joystickPointerPos.y = e.clientY;
  92837. this._deltaJoystickVector = this._joystickPointerPos.clone();
  92838. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  92839. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  92840. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  92841. switch (this._axisTargetedByLeftAndRight) {
  92842. case JoystickAxis.X:
  92843. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  92844. break;
  92845. case JoystickAxis.Y:
  92846. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  92847. break;
  92848. case JoystickAxis.Z:
  92849. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  92850. break;
  92851. }
  92852. var directionUpDown = this.reverseUpDown ? 1 : -1;
  92853. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  92854. switch (this._axisTargetedByUpAndDown) {
  92855. case JoystickAxis.X:
  92856. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  92857. break;
  92858. case JoystickAxis.Y:
  92859. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  92860. break;
  92861. case JoystickAxis.Z:
  92862. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  92863. break;
  92864. }
  92865. }
  92866. else {
  92867. var data = this._touches.get(e.pointerId.toString());
  92868. if (data) {
  92869. data.x = e.clientX;
  92870. data.y = e.clientY;
  92871. }
  92872. }
  92873. };
  92874. VirtualJoystick.prototype._onPointerUp = function (e) {
  92875. if (this._joystickPointerID == e.pointerId) {
  92876. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  92877. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  92878. this._joystickPointerID = -1;
  92879. this.pressed = false;
  92880. }
  92881. else {
  92882. var touch = this._touches.get(e.pointerId.toString());
  92883. if (touch) {
  92884. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  92885. }
  92886. }
  92887. this._deltaJoystickVector.x = 0;
  92888. this._deltaJoystickVector.y = 0;
  92889. this._touches.remove(e.pointerId.toString());
  92890. };
  92891. /**
  92892. * Change the color of the virtual joystick
  92893. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  92894. */
  92895. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  92896. this._joystickColor = newColor;
  92897. };
  92898. /**
  92899. * Defines a callback to call when the joystick is touched
  92900. * @param action defines the callback
  92901. */
  92902. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  92903. this._action = action;
  92904. };
  92905. /**
  92906. * Defines which axis you'd like to control for left & right
  92907. * @param axis defines the axis to use
  92908. */
  92909. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  92910. switch (axis) {
  92911. case JoystickAxis.X:
  92912. case JoystickAxis.Y:
  92913. case JoystickAxis.Z:
  92914. this._axisTargetedByLeftAndRight = axis;
  92915. break;
  92916. default:
  92917. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  92918. break;
  92919. }
  92920. };
  92921. /**
  92922. * Defines which axis you'd like to control for up & down
  92923. * @param axis defines the axis to use
  92924. */
  92925. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  92926. switch (axis) {
  92927. case JoystickAxis.X:
  92928. case JoystickAxis.Y:
  92929. case JoystickAxis.Z:
  92930. this._axisTargetedByUpAndDown = axis;
  92931. break;
  92932. default:
  92933. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  92934. break;
  92935. }
  92936. };
  92937. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  92938. var _this = this;
  92939. if (this.pressed) {
  92940. this._touches.forEach(function (key, touch) {
  92941. if (touch.pointerId === _this._joystickPointerID) {
  92942. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  92943. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  92944. VirtualJoystick.vjCanvasContext.beginPath();
  92945. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  92946. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  92947. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  92948. VirtualJoystick.vjCanvasContext.stroke();
  92949. VirtualJoystick.vjCanvasContext.closePath();
  92950. VirtualJoystick.vjCanvasContext.beginPath();
  92951. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  92952. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  92953. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  92954. VirtualJoystick.vjCanvasContext.stroke();
  92955. VirtualJoystick.vjCanvasContext.closePath();
  92956. VirtualJoystick.vjCanvasContext.beginPath();
  92957. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  92958. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  92959. VirtualJoystick.vjCanvasContext.stroke();
  92960. VirtualJoystick.vjCanvasContext.closePath();
  92961. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  92962. }
  92963. else {
  92964. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  92965. VirtualJoystick.vjCanvasContext.beginPath();
  92966. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  92967. VirtualJoystick.vjCanvasContext.beginPath();
  92968. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  92969. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  92970. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  92971. VirtualJoystick.vjCanvasContext.stroke();
  92972. VirtualJoystick.vjCanvasContext.closePath();
  92973. touch.prevX = touch.x;
  92974. touch.prevY = touch.y;
  92975. }
  92976. ;
  92977. });
  92978. }
  92979. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  92980. };
  92981. /**
  92982. * Release internal HTML canvas
  92983. */
  92984. VirtualJoystick.prototype.releaseCanvas = function () {
  92985. if (VirtualJoystick.vjCanvas) {
  92986. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  92987. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  92988. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  92989. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  92990. window.removeEventListener("resize", this._onResize);
  92991. document.body.removeChild(VirtualJoystick.vjCanvas);
  92992. VirtualJoystick.vjCanvas = null;
  92993. }
  92994. };
  92995. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  92996. VirtualJoystick._globalJoystickIndex = 0;
  92997. return VirtualJoystick;
  92998. }());
  92999. BABYLON.VirtualJoystick = VirtualJoystick;
  93000. })(BABYLON || (BABYLON = {}));
  93001. //# sourceMappingURL=babylon.virtualJoystick.js.map
  93002. var BABYLON;
  93003. (function (BABYLON) {
  93004. // We're mainly based on the logic defined into the FreeCamera code
  93005. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  93006. __extends(VirtualJoysticksCamera, _super);
  93007. function VirtualJoysticksCamera(name, position, scene) {
  93008. var _this = _super.call(this, name, position, scene) || this;
  93009. _this.inputs.addVirtualJoystick();
  93010. return _this;
  93011. }
  93012. VirtualJoysticksCamera.prototype.getClassName = function () {
  93013. return "VirtualJoysticksCamera";
  93014. };
  93015. return VirtualJoysticksCamera;
  93016. }(BABYLON.FreeCamera));
  93017. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  93018. })(BABYLON || (BABYLON = {}));
  93019. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  93020. var BABYLON;
  93021. (function (BABYLON) {
  93022. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  93023. function FreeCameraVirtualJoystickInput() {
  93024. }
  93025. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  93026. return this._leftjoystick;
  93027. };
  93028. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  93029. return this._rightjoystick;
  93030. };
  93031. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  93032. if (this._leftjoystick) {
  93033. var camera = this.camera;
  93034. var speed = camera._computeLocalCameraSpeed() * 50;
  93035. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  93036. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  93037. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  93038. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  93039. if (!this._leftjoystick.pressed) {
  93040. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  93041. }
  93042. if (!this._rightjoystick.pressed) {
  93043. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  93044. }
  93045. }
  93046. };
  93047. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  93048. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  93049. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  93050. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  93051. this._leftjoystick.setJoystickSensibility(0.15);
  93052. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  93053. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  93054. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  93055. this._rightjoystick.reverseUpDown = true;
  93056. this._rightjoystick.setJoystickSensibility(0.05);
  93057. this._rightjoystick.setJoystickColor("yellow");
  93058. };
  93059. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  93060. this._leftjoystick.releaseCanvas();
  93061. this._rightjoystick.releaseCanvas();
  93062. };
  93063. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  93064. return "FreeCameraVirtualJoystickInput";
  93065. };
  93066. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  93067. return "virtualJoystick";
  93068. };
  93069. return FreeCameraVirtualJoystickInput;
  93070. }());
  93071. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  93072. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  93073. })(BABYLON || (BABYLON = {}));
  93074. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  93075. var BABYLON;
  93076. (function (BABYLON) {
  93077. var SimplificationSettings = /** @class */ (function () {
  93078. function SimplificationSettings(quality, distance, optimizeMesh) {
  93079. this.quality = quality;
  93080. this.distance = distance;
  93081. this.optimizeMesh = optimizeMesh;
  93082. }
  93083. return SimplificationSettings;
  93084. }());
  93085. BABYLON.SimplificationSettings = SimplificationSettings;
  93086. var SimplificationQueue = /** @class */ (function () {
  93087. function SimplificationQueue() {
  93088. this.running = false;
  93089. this._simplificationArray = [];
  93090. }
  93091. SimplificationQueue.prototype.addTask = function (task) {
  93092. this._simplificationArray.push(task);
  93093. };
  93094. SimplificationQueue.prototype.executeNext = function () {
  93095. var task = this._simplificationArray.pop();
  93096. if (task) {
  93097. this.running = true;
  93098. this.runSimplification(task);
  93099. }
  93100. else {
  93101. this.running = false;
  93102. }
  93103. };
  93104. SimplificationQueue.prototype.runSimplification = function (task) {
  93105. var _this = this;
  93106. if (task.parallelProcessing) {
  93107. //parallel simplifier
  93108. task.settings.forEach(function (setting) {
  93109. var simplifier = _this.getSimplifier(task);
  93110. simplifier.simplify(setting, function (newMesh) {
  93111. task.mesh.addLODLevel(setting.distance, newMesh);
  93112. newMesh.isVisible = true;
  93113. //check if it is the last
  93114. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  93115. //all done, run the success callback.
  93116. task.successCallback();
  93117. }
  93118. _this.executeNext();
  93119. });
  93120. });
  93121. }
  93122. else {
  93123. //single simplifier.
  93124. var simplifier = this.getSimplifier(task);
  93125. var runDecimation = function (setting, callback) {
  93126. simplifier.simplify(setting, function (newMesh) {
  93127. task.mesh.addLODLevel(setting.distance, newMesh);
  93128. newMesh.isVisible = true;
  93129. //run the next quality level
  93130. callback();
  93131. });
  93132. };
  93133. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  93134. runDecimation(task.settings[loop.index], function () {
  93135. loop.executeNext();
  93136. });
  93137. }, function () {
  93138. //execution ended, run the success callback.
  93139. if (task.successCallback) {
  93140. task.successCallback();
  93141. }
  93142. _this.executeNext();
  93143. });
  93144. }
  93145. };
  93146. SimplificationQueue.prototype.getSimplifier = function (task) {
  93147. switch (task.simplificationType) {
  93148. case SimplificationType.QUADRATIC:
  93149. default:
  93150. return new QuadraticErrorSimplification(task.mesh);
  93151. }
  93152. };
  93153. return SimplificationQueue;
  93154. }());
  93155. BABYLON.SimplificationQueue = SimplificationQueue;
  93156. /**
  93157. * The implemented types of simplification
  93158. * At the moment only Quadratic Error Decimation is implemented
  93159. */
  93160. var SimplificationType;
  93161. (function (SimplificationType) {
  93162. /** Quadratic error decimation */
  93163. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  93164. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  93165. var DecimationTriangle = /** @class */ (function () {
  93166. function DecimationTriangle(vertices) {
  93167. this.vertices = vertices;
  93168. this.error = new Array(4);
  93169. this.deleted = false;
  93170. this.isDirty = false;
  93171. this.deletePending = false;
  93172. this.borderFactor = 0;
  93173. }
  93174. return DecimationTriangle;
  93175. }());
  93176. BABYLON.DecimationTriangle = DecimationTriangle;
  93177. var DecimationVertex = /** @class */ (function () {
  93178. function DecimationVertex(position, id) {
  93179. this.position = position;
  93180. this.id = id;
  93181. this.isBorder = true;
  93182. this.q = new QuadraticMatrix();
  93183. this.triangleCount = 0;
  93184. this.triangleStart = 0;
  93185. this.originalOffsets = [];
  93186. }
  93187. DecimationVertex.prototype.updatePosition = function (newPosition) {
  93188. this.position.copyFrom(newPosition);
  93189. };
  93190. return DecimationVertex;
  93191. }());
  93192. BABYLON.DecimationVertex = DecimationVertex;
  93193. var QuadraticMatrix = /** @class */ (function () {
  93194. function QuadraticMatrix(data) {
  93195. this.data = new Array(10);
  93196. for (var i = 0; i < 10; ++i) {
  93197. if (data && data[i]) {
  93198. this.data[i] = data[i];
  93199. }
  93200. else {
  93201. this.data[i] = 0;
  93202. }
  93203. }
  93204. }
  93205. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  93206. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  93207. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  93208. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  93209. return det;
  93210. };
  93211. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  93212. for (var i = 0; i < 10; ++i) {
  93213. this.data[i] += matrix.data[i];
  93214. }
  93215. };
  93216. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  93217. for (var i = 0; i < 10; ++i) {
  93218. this.data[i] += data[i];
  93219. }
  93220. };
  93221. QuadraticMatrix.prototype.add = function (matrix) {
  93222. var m = new QuadraticMatrix();
  93223. for (var i = 0; i < 10; ++i) {
  93224. m.data[i] = this.data[i] + matrix.data[i];
  93225. }
  93226. return m;
  93227. };
  93228. QuadraticMatrix.FromData = function (a, b, c, d) {
  93229. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  93230. };
  93231. //returning an array to avoid garbage collection
  93232. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  93233. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  93234. };
  93235. return QuadraticMatrix;
  93236. }());
  93237. BABYLON.QuadraticMatrix = QuadraticMatrix;
  93238. var Reference = /** @class */ (function () {
  93239. function Reference(vertexId, triangleId) {
  93240. this.vertexId = vertexId;
  93241. this.triangleId = triangleId;
  93242. }
  93243. return Reference;
  93244. }());
  93245. BABYLON.Reference = Reference;
  93246. /**
  93247. * An implementation of the Quadratic Error simplification algorithm.
  93248. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  93249. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  93250. * @author RaananW
  93251. */
  93252. var QuadraticErrorSimplification = /** @class */ (function () {
  93253. function QuadraticErrorSimplification(_mesh) {
  93254. this._mesh = _mesh;
  93255. this.syncIterations = 5000;
  93256. this.aggressiveness = 7;
  93257. this.decimationIterations = 100;
  93258. this.boundingBoxEpsilon = BABYLON.Epsilon;
  93259. }
  93260. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  93261. var _this = this;
  93262. this.initDecimatedMesh();
  93263. //iterating through the submeshes array, one after the other.
  93264. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  93265. _this.initWithMesh(loop.index, function () {
  93266. _this.runDecimation(settings, loop.index, function () {
  93267. loop.executeNext();
  93268. });
  93269. }, settings.optimizeMesh);
  93270. }, function () {
  93271. setTimeout(function () {
  93272. successCallback(_this._reconstructedMesh);
  93273. }, 0);
  93274. });
  93275. };
  93276. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  93277. var _this = this;
  93278. var targetCount = ~~(this.triangles.length * settings.quality);
  93279. var deletedTriangles = 0;
  93280. var triangleCount = this.triangles.length;
  93281. var iterationFunction = function (iteration, callback) {
  93282. setTimeout(function () {
  93283. if (iteration % 5 === 0) {
  93284. _this.updateMesh(iteration === 0);
  93285. }
  93286. for (var i = 0; i < _this.triangles.length; ++i) {
  93287. _this.triangles[i].isDirty = false;
  93288. }
  93289. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  93290. var trianglesIterator = function (i) {
  93291. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  93292. var t = _this.triangles[tIdx];
  93293. if (!t)
  93294. return;
  93295. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  93296. return;
  93297. }
  93298. for (var j = 0; j < 3; ++j) {
  93299. if (t.error[j] < threshold) {
  93300. var deleted0 = [];
  93301. var deleted1 = [];
  93302. var v0 = t.vertices[j];
  93303. var v1 = t.vertices[(j + 1) % 3];
  93304. if (v0.isBorder || v1.isBorder)
  93305. continue;
  93306. var p = BABYLON.Vector3.Zero();
  93307. var n = BABYLON.Vector3.Zero();
  93308. var uv = BABYLON.Vector2.Zero();
  93309. var color = new BABYLON.Color4(0, 0, 0, 1);
  93310. _this.calculateError(v0, v1, p, n, uv, color);
  93311. var delTr = new Array();
  93312. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  93313. continue;
  93314. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  93315. continue;
  93316. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  93317. continue;
  93318. var uniqueArray = new Array();
  93319. delTr.forEach(function (deletedT) {
  93320. if (uniqueArray.indexOf(deletedT) === -1) {
  93321. deletedT.deletePending = true;
  93322. uniqueArray.push(deletedT);
  93323. }
  93324. });
  93325. if (uniqueArray.length % 2 !== 0) {
  93326. continue;
  93327. }
  93328. v0.q = v1.q.add(v0.q);
  93329. v0.updatePosition(p);
  93330. var tStart = _this.references.length;
  93331. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  93332. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  93333. var tCount = _this.references.length - tStart;
  93334. if (tCount <= v0.triangleCount) {
  93335. if (tCount) {
  93336. for (var c = 0; c < tCount; c++) {
  93337. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  93338. }
  93339. }
  93340. }
  93341. else {
  93342. v0.triangleStart = tStart;
  93343. }
  93344. v0.triangleCount = tCount;
  93345. break;
  93346. }
  93347. }
  93348. };
  93349. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  93350. }, 0);
  93351. };
  93352. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  93353. if (triangleCount - deletedTriangles <= targetCount)
  93354. loop.breakLoop();
  93355. else {
  93356. iterationFunction(loop.index, function () {
  93357. loop.executeNext();
  93358. });
  93359. }
  93360. }, function () {
  93361. setTimeout(function () {
  93362. //reconstruct this part of the mesh
  93363. _this.reconstructMesh(submeshIndex);
  93364. successCallback();
  93365. }, 0);
  93366. });
  93367. };
  93368. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  93369. var _this = this;
  93370. this.vertices = [];
  93371. this.triangles = [];
  93372. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  93373. var indices = this._mesh.getIndices();
  93374. var submesh = this._mesh.subMeshes[submeshIndex];
  93375. var findInVertices = function (positionToSearch) {
  93376. if (optimizeMesh) {
  93377. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  93378. if (_this.vertices[ii].position.equals(positionToSearch)) {
  93379. return _this.vertices[ii];
  93380. }
  93381. }
  93382. }
  93383. return null;
  93384. };
  93385. var vertexReferences = [];
  93386. var vertexInit = function (i) {
  93387. if (!positionData) {
  93388. return;
  93389. }
  93390. var offset = i + submesh.verticesStart;
  93391. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  93392. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  93393. vertex.originalOffsets.push(offset);
  93394. if (vertex.id === _this.vertices.length) {
  93395. _this.vertices.push(vertex);
  93396. }
  93397. vertexReferences.push(vertex.id);
  93398. };
  93399. //var totalVertices = mesh.getTotalVertices();
  93400. var totalVertices = submesh.verticesCount;
  93401. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  93402. var indicesInit = function (i) {
  93403. if (!indices) {
  93404. return;
  93405. }
  93406. var offset = (submesh.indexStart / 3) + i;
  93407. var pos = (offset * 3);
  93408. var i0 = indices[pos + 0];
  93409. var i1 = indices[pos + 1];
  93410. var i2 = indices[pos + 2];
  93411. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  93412. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  93413. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  93414. var triangle = new DecimationTriangle([v0, v1, v2]);
  93415. triangle.originalOffset = pos;
  93416. _this.triangles.push(triangle);
  93417. };
  93418. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  93419. _this.init(callback);
  93420. });
  93421. });
  93422. };
  93423. QuadraticErrorSimplification.prototype.init = function (callback) {
  93424. var _this = this;
  93425. var triangleInit1 = function (i) {
  93426. var t = _this.triangles[i];
  93427. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  93428. for (var j = 0; j < 3; j++) {
  93429. 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))));
  93430. }
  93431. };
  93432. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  93433. var triangleInit2 = function (i) {
  93434. var t = _this.triangles[i];
  93435. for (var j = 0; j < 3; ++j) {
  93436. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  93437. }
  93438. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  93439. };
  93440. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  93441. callback();
  93442. });
  93443. });
  93444. };
  93445. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  93446. var newTriangles = [];
  93447. var i;
  93448. for (i = 0; i < this.vertices.length; ++i) {
  93449. this.vertices[i].triangleCount = 0;
  93450. }
  93451. var t;
  93452. var j;
  93453. for (i = 0; i < this.triangles.length; ++i) {
  93454. if (!this.triangles[i].deleted) {
  93455. t = this.triangles[i];
  93456. for (j = 0; j < 3; ++j) {
  93457. t.vertices[j].triangleCount = 1;
  93458. }
  93459. newTriangles.push(t);
  93460. }
  93461. }
  93462. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  93463. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  93464. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  93465. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  93466. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  93467. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  93468. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  93469. var vertexCount = 0;
  93470. for (i = 0; i < this.vertices.length; ++i) {
  93471. var vertex = this.vertices[i];
  93472. vertex.id = vertexCount;
  93473. if (vertex.triangleCount) {
  93474. vertex.originalOffsets.forEach(function (originalOffset) {
  93475. if (!normalData) {
  93476. return;
  93477. }
  93478. newPositionData.push(vertex.position.x);
  93479. newPositionData.push(vertex.position.y);
  93480. newPositionData.push(vertex.position.z);
  93481. newNormalData.push(normalData[originalOffset * 3]);
  93482. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  93483. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  93484. if (uvs && uvs.length) {
  93485. newUVsData.push(uvs[(originalOffset * 2)]);
  93486. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  93487. }
  93488. else if (colorsData && colorsData.length) {
  93489. newColorsData.push(colorsData[(originalOffset * 4)]);
  93490. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  93491. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  93492. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  93493. }
  93494. ++vertexCount;
  93495. });
  93496. }
  93497. }
  93498. var startingIndex = this._reconstructedMesh.getTotalIndices();
  93499. var startingVertex = this._reconstructedMesh.getTotalVertices();
  93500. var submeshesArray = this._reconstructedMesh.subMeshes;
  93501. this._reconstructedMesh.subMeshes = [];
  93502. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  93503. var originalIndices = this._mesh.getIndices();
  93504. for (i = 0; i < newTriangles.length; ++i) {
  93505. t = newTriangles[i]; //now get the new referencing point for each vertex
  93506. [0, 1, 2].forEach(function (idx) {
  93507. var id = originalIndices[t.originalOffset + idx];
  93508. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  93509. if (offset < 0)
  93510. offset = 0;
  93511. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  93512. });
  93513. }
  93514. //overwriting the old vertex buffers and indices.
  93515. this._reconstructedMesh.setIndices(newIndicesArray);
  93516. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  93517. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  93518. if (newUVsData.length > 0)
  93519. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  93520. if (newColorsData.length > 0)
  93521. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  93522. //create submesh
  93523. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  93524. if (submeshIndex > 0) {
  93525. this._reconstructedMesh.subMeshes = [];
  93526. submeshesArray.forEach(function (submesh) {
  93527. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  93528. });
  93529. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  93530. }
  93531. };
  93532. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  93533. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  93534. this._reconstructedMesh.material = this._mesh.material;
  93535. this._reconstructedMesh.parent = this._mesh.parent;
  93536. this._reconstructedMesh.isVisible = false;
  93537. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  93538. };
  93539. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  93540. for (var i = 0; i < vertex1.triangleCount; ++i) {
  93541. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  93542. if (t.deleted)
  93543. continue;
  93544. var s = this.references[vertex1.triangleStart + i].vertexId;
  93545. var v1 = t.vertices[(s + 1) % 3];
  93546. var v2 = t.vertices[(s + 2) % 3];
  93547. if ((v1 === vertex2 || v2 === vertex2)) {
  93548. deletedArray[i] = true;
  93549. delTr.push(t);
  93550. continue;
  93551. }
  93552. var d1 = v1.position.subtract(point);
  93553. d1 = d1.normalize();
  93554. var d2 = v2.position.subtract(point);
  93555. d2 = d2.normalize();
  93556. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  93557. return true;
  93558. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  93559. deletedArray[i] = false;
  93560. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  93561. return true;
  93562. }
  93563. return false;
  93564. };
  93565. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  93566. var newDeleted = deletedTriangles;
  93567. for (var i = 0; i < vertex.triangleCount; ++i) {
  93568. var ref = this.references[vertex.triangleStart + i];
  93569. var t = this.triangles[ref.triangleId];
  93570. if (t.deleted)
  93571. continue;
  93572. if (deletedArray[i] && t.deletePending) {
  93573. t.deleted = true;
  93574. newDeleted++;
  93575. continue;
  93576. }
  93577. t.vertices[ref.vertexId] = origVertex;
  93578. t.isDirty = true;
  93579. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  93580. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  93581. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  93582. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  93583. this.references.push(ref);
  93584. }
  93585. return newDeleted;
  93586. };
  93587. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  93588. for (var i = 0; i < this.vertices.length; ++i) {
  93589. var vCount = [];
  93590. var vId = [];
  93591. var v = this.vertices[i];
  93592. var j;
  93593. for (j = 0; j < v.triangleCount; ++j) {
  93594. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  93595. for (var ii = 0; ii < 3; ii++) {
  93596. var ofs = 0;
  93597. var vv = triangle.vertices[ii];
  93598. while (ofs < vCount.length) {
  93599. if (vId[ofs] === vv.id)
  93600. break;
  93601. ++ofs;
  93602. }
  93603. if (ofs === vCount.length) {
  93604. vCount.push(1);
  93605. vId.push(vv.id);
  93606. }
  93607. else {
  93608. vCount[ofs]++;
  93609. }
  93610. }
  93611. }
  93612. for (j = 0; j < vCount.length; ++j) {
  93613. if (vCount[j] === 1) {
  93614. this.vertices[vId[j]].isBorder = true;
  93615. }
  93616. else {
  93617. this.vertices[vId[j]].isBorder = false;
  93618. }
  93619. }
  93620. }
  93621. };
  93622. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  93623. if (identifyBorders === void 0) { identifyBorders = false; }
  93624. var i;
  93625. if (!identifyBorders) {
  93626. var newTrianglesVector = [];
  93627. for (i = 0; i < this.triangles.length; ++i) {
  93628. if (!this.triangles[i].deleted) {
  93629. newTrianglesVector.push(this.triangles[i]);
  93630. }
  93631. }
  93632. this.triangles = newTrianglesVector;
  93633. }
  93634. for (i = 0; i < this.vertices.length; ++i) {
  93635. this.vertices[i].triangleCount = 0;
  93636. this.vertices[i].triangleStart = 0;
  93637. }
  93638. var t;
  93639. var j;
  93640. var v;
  93641. for (i = 0; i < this.triangles.length; ++i) {
  93642. t = this.triangles[i];
  93643. for (j = 0; j < 3; ++j) {
  93644. v = t.vertices[j];
  93645. v.triangleCount++;
  93646. }
  93647. }
  93648. var tStart = 0;
  93649. for (i = 0; i < this.vertices.length; ++i) {
  93650. this.vertices[i].triangleStart = tStart;
  93651. tStart += this.vertices[i].triangleCount;
  93652. this.vertices[i].triangleCount = 0;
  93653. }
  93654. var newReferences = new Array(this.triangles.length * 3);
  93655. for (i = 0; i < this.triangles.length; ++i) {
  93656. t = this.triangles[i];
  93657. for (j = 0; j < 3; ++j) {
  93658. v = t.vertices[j];
  93659. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  93660. v.triangleCount++;
  93661. }
  93662. }
  93663. this.references = newReferences;
  93664. if (identifyBorders) {
  93665. this.identifyBorder();
  93666. }
  93667. };
  93668. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  93669. var x = point.x;
  93670. var y = point.y;
  93671. var z = point.z;
  93672. 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
  93673. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  93674. };
  93675. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  93676. var q = vertex1.q.add(vertex2.q);
  93677. var border = vertex1.isBorder && vertex2.isBorder;
  93678. var error = 0;
  93679. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  93680. if (qDet !== 0 && !border) {
  93681. if (!pointResult) {
  93682. pointResult = BABYLON.Vector3.Zero();
  93683. }
  93684. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  93685. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  93686. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  93687. error = this.vertexError(q, pointResult);
  93688. }
  93689. else {
  93690. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  93691. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  93692. var error1 = this.vertexError(q, vertex1.position);
  93693. var error2 = this.vertexError(q, vertex2.position);
  93694. var error3 = this.vertexError(q, p3);
  93695. error = Math.min(error1, error2, error3);
  93696. if (error === error1) {
  93697. if (pointResult) {
  93698. pointResult.copyFrom(vertex1.position);
  93699. }
  93700. }
  93701. else if (error === error2) {
  93702. if (pointResult) {
  93703. pointResult.copyFrom(vertex2.position);
  93704. }
  93705. }
  93706. else {
  93707. if (pointResult) {
  93708. pointResult.copyFrom(p3);
  93709. }
  93710. }
  93711. }
  93712. return error;
  93713. };
  93714. return QuadraticErrorSimplification;
  93715. }());
  93716. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  93717. })(BABYLON || (BABYLON = {}));
  93718. //# sourceMappingURL=babylon.meshSimplification.js.map
  93719. var BABYLON;
  93720. (function (BABYLON) {
  93721. var MeshLODLevel = /** @class */ (function () {
  93722. function MeshLODLevel(distance, mesh) {
  93723. this.distance = distance;
  93724. this.mesh = mesh;
  93725. }
  93726. return MeshLODLevel;
  93727. }());
  93728. BABYLON.MeshLODLevel = MeshLODLevel;
  93729. })(BABYLON || (BABYLON = {}));
  93730. //# sourceMappingURL=babylon.meshLODLevel.js.map
  93731. var BABYLON;
  93732. (function (BABYLON) {
  93733. /**
  93734. * Defines the root class used to create scene optimization to use with SceneOptimizer
  93735. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93736. */
  93737. var SceneOptimization = /** @class */ (function () {
  93738. /**
  93739. * Creates the SceneOptimization object
  93740. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  93741. * @param desc defines the description associated with the optimization
  93742. */
  93743. function SceneOptimization(
  93744. /**
  93745. * Defines the priority of this optimization (0 by default which means first in the list)
  93746. */
  93747. priority) {
  93748. if (priority === void 0) { priority = 0; }
  93749. this.priority = priority;
  93750. }
  93751. /**
  93752. * Gets a string describing the action executed by the current optimization
  93753. * @returns description string
  93754. */
  93755. SceneOptimization.prototype.getDescription = function () {
  93756. return "";
  93757. };
  93758. /**
  93759. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93760. * @param scene defines the current scene where to apply this optimization
  93761. * @param optimizer defines the current optimizer
  93762. * @returns true if everything that can be done was applied
  93763. */
  93764. SceneOptimization.prototype.apply = function (scene, optimizer) {
  93765. return true;
  93766. };
  93767. ;
  93768. return SceneOptimization;
  93769. }());
  93770. BABYLON.SceneOptimization = SceneOptimization;
  93771. /**
  93772. * Defines an optimization used to reduce the size of render target textures
  93773. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93774. */
  93775. var TextureOptimization = /** @class */ (function (_super) {
  93776. __extends(TextureOptimization, _super);
  93777. /**
  93778. * Creates the TextureOptimization object
  93779. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  93780. * @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
  93781. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  93782. */
  93783. function TextureOptimization(
  93784. /**
  93785. * Defines the priority of this optimization (0 by default which means first in the list)
  93786. */
  93787. priority,
  93788. /**
  93789. * 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
  93790. */
  93791. maximumSize,
  93792. /**
  93793. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  93794. */
  93795. step) {
  93796. if (priority === void 0) { priority = 0; }
  93797. if (maximumSize === void 0) { maximumSize = 1024; }
  93798. if (step === void 0) { step = 0.5; }
  93799. var _this = _super.call(this, priority) || this;
  93800. _this.priority = priority;
  93801. _this.maximumSize = maximumSize;
  93802. _this.step = step;
  93803. return _this;
  93804. }
  93805. /**
  93806. * Gets a string describing the action executed by the current optimization
  93807. * @returns description string
  93808. */
  93809. TextureOptimization.prototype.getDescription = function () {
  93810. return "Reducing render target texture size to " + this.maximumSize;
  93811. };
  93812. /**
  93813. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93814. * @param scene defines the current scene where to apply this optimization
  93815. * @param optimizer defines the current optimizer
  93816. * @returns true if everything that can be done was applied
  93817. */
  93818. TextureOptimization.prototype.apply = function (scene, optimizer) {
  93819. var allDone = true;
  93820. for (var index = 0; index < scene.textures.length; index++) {
  93821. var texture = scene.textures[index];
  93822. if (!texture.canRescale || texture.getContext) {
  93823. continue;
  93824. }
  93825. var currentSize = texture.getSize();
  93826. var maxDimension = Math.max(currentSize.width, currentSize.height);
  93827. if (maxDimension > this.maximumSize) {
  93828. texture.scale(this.step);
  93829. allDone = false;
  93830. }
  93831. }
  93832. return allDone;
  93833. };
  93834. return TextureOptimization;
  93835. }(SceneOptimization));
  93836. BABYLON.TextureOptimization = TextureOptimization;
  93837. /**
  93838. * Defines an optimization used to increase or decrease the rendering resolution
  93839. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93840. */
  93841. var HardwareScalingOptimization = /** @class */ (function (_super) {
  93842. __extends(HardwareScalingOptimization, _super);
  93843. /**
  93844. * Creates the HardwareScalingOptimization object
  93845. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  93846. * @param maximumScale defines the maximum scale to use (2 by default)
  93847. * @param step defines the step to use between two passes (0.5 by default)
  93848. */
  93849. function HardwareScalingOptimization(
  93850. /**
  93851. * Defines the priority of this optimization (0 by default which means first in the list)
  93852. */
  93853. priority,
  93854. /**
  93855. * Defines the maximum scale to use (2 by default)
  93856. */
  93857. maximumScale,
  93858. /**
  93859. * Defines the step to use between two passes (0.5 by default)
  93860. */
  93861. step) {
  93862. if (priority === void 0) { priority = 0; }
  93863. if (maximumScale === void 0) { maximumScale = 2; }
  93864. if (step === void 0) { step = 0.25; }
  93865. var _this = _super.call(this, priority) || this;
  93866. _this.priority = priority;
  93867. _this.maximumScale = maximumScale;
  93868. _this.step = step;
  93869. _this._currentScale = -1;
  93870. _this._directionOffset = 1;
  93871. return _this;
  93872. }
  93873. /**
  93874. * Gets a string describing the action executed by the current optimization
  93875. * @return description string
  93876. */
  93877. HardwareScalingOptimization.prototype.getDescription = function () {
  93878. return "Setting hardware scaling level to " + this._currentScale;
  93879. };
  93880. /**
  93881. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93882. * @param scene defines the current scene where to apply this optimization
  93883. * @param optimizer defines the current optimizer
  93884. * @returns true if everything that can be done was applied
  93885. */
  93886. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  93887. if (this._currentScale === -1) {
  93888. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  93889. if (this._currentScale > this.maximumScale) {
  93890. this._directionOffset = -1;
  93891. }
  93892. }
  93893. this._currentScale += this._directionOffset * this.step;
  93894. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  93895. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  93896. };
  93897. ;
  93898. return HardwareScalingOptimization;
  93899. }(SceneOptimization));
  93900. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  93901. /**
  93902. * Defines an optimization used to remove shadows
  93903. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93904. */
  93905. var ShadowsOptimization = /** @class */ (function (_super) {
  93906. __extends(ShadowsOptimization, _super);
  93907. function ShadowsOptimization() {
  93908. return _super !== null && _super.apply(this, arguments) || this;
  93909. }
  93910. /**
  93911. * Gets a string describing the action executed by the current optimization
  93912. * @return description string
  93913. */
  93914. ShadowsOptimization.prototype.getDescription = function () {
  93915. return "Turning shadows on/off";
  93916. };
  93917. /**
  93918. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93919. * @param scene defines the current scene where to apply this optimization
  93920. * @param optimizer defines the current optimizer
  93921. * @returns true if everything that can be done was applied
  93922. */
  93923. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  93924. scene.shadowsEnabled = optimizer.isInImprovementMode;
  93925. return true;
  93926. };
  93927. ;
  93928. return ShadowsOptimization;
  93929. }(SceneOptimization));
  93930. BABYLON.ShadowsOptimization = ShadowsOptimization;
  93931. /**
  93932. * Defines an optimization used to turn post-processes off
  93933. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93934. */
  93935. var PostProcessesOptimization = /** @class */ (function (_super) {
  93936. __extends(PostProcessesOptimization, _super);
  93937. function PostProcessesOptimization() {
  93938. return _super !== null && _super.apply(this, arguments) || this;
  93939. }
  93940. /**
  93941. * Gets a string describing the action executed by the current optimization
  93942. * @return description string
  93943. */
  93944. PostProcessesOptimization.prototype.getDescription = function () {
  93945. return "Turning post-processes on/off";
  93946. };
  93947. /**
  93948. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93949. * @param scene defines the current scene where to apply this optimization
  93950. * @param optimizer defines the current optimizer
  93951. * @returns true if everything that can be done was applied
  93952. */
  93953. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  93954. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  93955. return true;
  93956. };
  93957. ;
  93958. return PostProcessesOptimization;
  93959. }(SceneOptimization));
  93960. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  93961. /**
  93962. * Defines an optimization used to turn lens flares off
  93963. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93964. */
  93965. var LensFlaresOptimization = /** @class */ (function (_super) {
  93966. __extends(LensFlaresOptimization, _super);
  93967. function LensFlaresOptimization() {
  93968. return _super !== null && _super.apply(this, arguments) || this;
  93969. }
  93970. /**
  93971. * Gets a string describing the action executed by the current optimization
  93972. * @return description string
  93973. */
  93974. LensFlaresOptimization.prototype.getDescription = function () {
  93975. return "Turning lens flares on/off";
  93976. };
  93977. /**
  93978. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93979. * @param scene defines the current scene where to apply this optimization
  93980. * @param optimizer defines the current optimizer
  93981. * @returns true if everything that can be done was applied
  93982. */
  93983. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  93984. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  93985. return true;
  93986. };
  93987. ;
  93988. return LensFlaresOptimization;
  93989. }(SceneOptimization));
  93990. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  93991. /**
  93992. * Defines an optimization based on user defined callback.
  93993. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93994. */
  93995. var CustomOptimization = /** @class */ (function (_super) {
  93996. __extends(CustomOptimization, _super);
  93997. function CustomOptimization() {
  93998. return _super !== null && _super.apply(this, arguments) || this;
  93999. }
  94000. /**
  94001. * Gets a string describing the action executed by the current optimization
  94002. * @returns description string
  94003. */
  94004. CustomOptimization.prototype.getDescription = function () {
  94005. if (this.onGetDescription) {
  94006. return this.onGetDescription();
  94007. }
  94008. return "Running user defined callback";
  94009. };
  94010. /**
  94011. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94012. * @param scene defines the current scene where to apply this optimization
  94013. * @param optimizer defines the current optimizer
  94014. * @returns true if everything that can be done was applied
  94015. */
  94016. CustomOptimization.prototype.apply = function (scene, optimizer) {
  94017. if (this.onApply) {
  94018. return this.onApply(scene, optimizer);
  94019. }
  94020. return true;
  94021. };
  94022. ;
  94023. return CustomOptimization;
  94024. }(SceneOptimization));
  94025. BABYLON.CustomOptimization = CustomOptimization;
  94026. /**
  94027. * Defines an optimization used to turn particles off
  94028. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94029. */
  94030. var ParticlesOptimization = /** @class */ (function (_super) {
  94031. __extends(ParticlesOptimization, _super);
  94032. function ParticlesOptimization() {
  94033. return _super !== null && _super.apply(this, arguments) || this;
  94034. }
  94035. /**
  94036. * Gets a string describing the action executed by the current optimization
  94037. * @return description string
  94038. */
  94039. ParticlesOptimization.prototype.getDescription = function () {
  94040. return "Turning particles on/off";
  94041. };
  94042. /**
  94043. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94044. * @param scene defines the current scene where to apply this optimization
  94045. * @param optimizer defines the current optimizer
  94046. * @returns true if everything that can be done was applied
  94047. */
  94048. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  94049. scene.particlesEnabled = optimizer.isInImprovementMode;
  94050. return true;
  94051. };
  94052. ;
  94053. return ParticlesOptimization;
  94054. }(SceneOptimization));
  94055. BABYLON.ParticlesOptimization = ParticlesOptimization;
  94056. /**
  94057. * Defines an optimization used to turn render targets off
  94058. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94059. */
  94060. var RenderTargetsOptimization = /** @class */ (function (_super) {
  94061. __extends(RenderTargetsOptimization, _super);
  94062. function RenderTargetsOptimization() {
  94063. return _super !== null && _super.apply(this, arguments) || this;
  94064. }
  94065. /**
  94066. * Gets a string describing the action executed by the current optimization
  94067. * @return description string
  94068. */
  94069. RenderTargetsOptimization.prototype.getDescription = function () {
  94070. return "Turning render targets off";
  94071. };
  94072. /**
  94073. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94074. * @param scene defines the current scene where to apply this optimization
  94075. * @param optimizer defines the current optimizer
  94076. * @returns true if everything that can be done was applied
  94077. */
  94078. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  94079. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  94080. return true;
  94081. };
  94082. ;
  94083. return RenderTargetsOptimization;
  94084. }(SceneOptimization));
  94085. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  94086. /**
  94087. * Defines an optimization used to merge meshes with compatible materials
  94088. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94089. */
  94090. var MergeMeshesOptimization = /** @class */ (function (_super) {
  94091. __extends(MergeMeshesOptimization, _super);
  94092. function MergeMeshesOptimization() {
  94093. var _this = _super !== null && _super.apply(this, arguments) || this;
  94094. _this._canBeMerged = function (abstractMesh) {
  94095. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  94096. return false;
  94097. }
  94098. var mesh = abstractMesh;
  94099. if (!mesh.isVisible || !mesh.isEnabled()) {
  94100. return false;
  94101. }
  94102. if (mesh.instances.length > 0) {
  94103. return false;
  94104. }
  94105. if (mesh.skeleton || mesh.hasLODLevels) {
  94106. return false;
  94107. }
  94108. if (mesh.parent) {
  94109. return false;
  94110. }
  94111. return true;
  94112. };
  94113. return _this;
  94114. }
  94115. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  94116. /**
  94117. * Gets or sets a boolean which defines if optimization octree has to be updated
  94118. */
  94119. get: function () {
  94120. return MergeMeshesOptimization._UpdateSelectionTree;
  94121. },
  94122. /**
  94123. * Gets or sets a boolean which defines if optimization octree has to be updated
  94124. */
  94125. set: function (value) {
  94126. MergeMeshesOptimization._UpdateSelectionTree = value;
  94127. },
  94128. enumerable: true,
  94129. configurable: true
  94130. });
  94131. /**
  94132. * Gets a string describing the action executed by the current optimization
  94133. * @return description string
  94134. */
  94135. MergeMeshesOptimization.prototype.getDescription = function () {
  94136. return "Merging similar meshes together";
  94137. };
  94138. /**
  94139. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94140. * @param scene defines the current scene where to apply this optimization
  94141. * @param optimizer defines the current optimizer
  94142. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  94143. * @returns true if everything that can be done was applied
  94144. */
  94145. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  94146. var globalPool = scene.meshes.slice(0);
  94147. var globalLength = globalPool.length;
  94148. for (var index = 0; index < globalLength; index++) {
  94149. var currentPool = new Array();
  94150. var current = globalPool[index];
  94151. // Checks
  94152. if (!this._canBeMerged(current)) {
  94153. continue;
  94154. }
  94155. currentPool.push(current);
  94156. // Find compatible meshes
  94157. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  94158. var otherMesh = globalPool[subIndex];
  94159. if (!this._canBeMerged(otherMesh)) {
  94160. continue;
  94161. }
  94162. if (otherMesh.material !== current.material) {
  94163. continue;
  94164. }
  94165. if (otherMesh.checkCollisions !== current.checkCollisions) {
  94166. continue;
  94167. }
  94168. currentPool.push(otherMesh);
  94169. globalLength--;
  94170. globalPool.splice(subIndex, 1);
  94171. subIndex--;
  94172. }
  94173. if (currentPool.length < 2) {
  94174. continue;
  94175. }
  94176. // Merge meshes
  94177. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  94178. }
  94179. if (updateSelectionTree != undefined) {
  94180. if (updateSelectionTree) {
  94181. scene.createOrUpdateSelectionOctree();
  94182. }
  94183. }
  94184. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  94185. scene.createOrUpdateSelectionOctree();
  94186. }
  94187. return true;
  94188. };
  94189. ;
  94190. MergeMeshesOptimization._UpdateSelectionTree = false;
  94191. return MergeMeshesOptimization;
  94192. }(SceneOptimization));
  94193. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  94194. /**
  94195. * Defines a list of options used by SceneOptimizer
  94196. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94197. */
  94198. var SceneOptimizerOptions = /** @class */ (function () {
  94199. /**
  94200. * Creates a new list of options used by SceneOptimizer
  94201. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  94202. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  94203. */
  94204. function SceneOptimizerOptions(
  94205. /**
  94206. * Defines the target frame rate to reach (60 by default)
  94207. */
  94208. targetFrameRate,
  94209. /**
  94210. * Defines the interval between two checkes (2000ms by default)
  94211. */
  94212. trackerDuration) {
  94213. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  94214. if (trackerDuration === void 0) { trackerDuration = 2000; }
  94215. this.targetFrameRate = targetFrameRate;
  94216. this.trackerDuration = trackerDuration;
  94217. /**
  94218. * Gets the list of optimizations to apply
  94219. */
  94220. this.optimizations = new Array();
  94221. }
  94222. /**
  94223. * Add a new optimization
  94224. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  94225. * @returns the current SceneOptimizerOptions
  94226. */
  94227. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  94228. this.optimizations.push(optimization);
  94229. return this;
  94230. };
  94231. /**
  94232. * Add a new custom optimization
  94233. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  94234. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  94235. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94236. * @returns the current SceneOptimizerOptions
  94237. */
  94238. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  94239. if (priority === void 0) { priority = 0; }
  94240. var optimization = new CustomOptimization(priority);
  94241. optimization.onApply = onApply;
  94242. optimization.onGetDescription = onGetDescription;
  94243. this.optimizations.push(optimization);
  94244. return this;
  94245. };
  94246. /**
  94247. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  94248. * @param targetFrameRate defines the target frame rate (60 by default)
  94249. * @returns a SceneOptimizerOptions object
  94250. */
  94251. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  94252. var result = new SceneOptimizerOptions(targetFrameRate);
  94253. var priority = 0;
  94254. result.addOptimization(new MergeMeshesOptimization(priority));
  94255. result.addOptimization(new ShadowsOptimization(priority));
  94256. result.addOptimization(new LensFlaresOptimization(priority));
  94257. // Next priority
  94258. priority++;
  94259. result.addOptimization(new PostProcessesOptimization(priority));
  94260. result.addOptimization(new ParticlesOptimization(priority));
  94261. // Next priority
  94262. priority++;
  94263. result.addOptimization(new TextureOptimization(priority, 1024));
  94264. return result;
  94265. };
  94266. /**
  94267. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  94268. * @param targetFrameRate defines the target frame rate (60 by default)
  94269. * @returns a SceneOptimizerOptions object
  94270. */
  94271. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  94272. var result = new SceneOptimizerOptions(targetFrameRate);
  94273. var priority = 0;
  94274. result.addOptimization(new MergeMeshesOptimization(priority));
  94275. result.addOptimization(new ShadowsOptimization(priority));
  94276. result.addOptimization(new LensFlaresOptimization(priority));
  94277. // Next priority
  94278. priority++;
  94279. result.addOptimization(new PostProcessesOptimization(priority));
  94280. result.addOptimization(new ParticlesOptimization(priority));
  94281. // Next priority
  94282. priority++;
  94283. result.addOptimization(new TextureOptimization(priority, 512));
  94284. // Next priority
  94285. priority++;
  94286. result.addOptimization(new RenderTargetsOptimization(priority));
  94287. // Next priority
  94288. priority++;
  94289. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  94290. return result;
  94291. };
  94292. /**
  94293. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  94294. * @param targetFrameRate defines the target frame rate (60 by default)
  94295. * @returns a SceneOptimizerOptions object
  94296. */
  94297. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  94298. var result = new SceneOptimizerOptions(targetFrameRate);
  94299. var priority = 0;
  94300. result.addOptimization(new MergeMeshesOptimization(priority));
  94301. result.addOptimization(new ShadowsOptimization(priority));
  94302. result.addOptimization(new LensFlaresOptimization(priority));
  94303. // Next priority
  94304. priority++;
  94305. result.addOptimization(new PostProcessesOptimization(priority));
  94306. result.addOptimization(new ParticlesOptimization(priority));
  94307. // Next priority
  94308. priority++;
  94309. result.addOptimization(new TextureOptimization(priority, 256));
  94310. // Next priority
  94311. priority++;
  94312. result.addOptimization(new RenderTargetsOptimization(priority));
  94313. // Next priority
  94314. priority++;
  94315. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  94316. return result;
  94317. };
  94318. return SceneOptimizerOptions;
  94319. }());
  94320. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  94321. /**
  94322. * Class used to run optimizations in order to reach a target frame rate
  94323. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94324. */
  94325. var SceneOptimizer = /** @class */ (function () {
  94326. /**
  94327. * Creates a new SceneOptimizer
  94328. * @param scene defines the scene to work on
  94329. * @param options defines the options to use with the SceneOptimizer
  94330. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  94331. * @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)
  94332. */
  94333. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  94334. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  94335. if (improvementMode === void 0) { improvementMode = false; }
  94336. var _this = this;
  94337. this._isRunning = false;
  94338. this._currentPriorityLevel = 0;
  94339. this._targetFrameRate = 60;
  94340. this._trackerDuration = 2000;
  94341. this._currentFrameRate = 0;
  94342. this._improvementMode = false;
  94343. /**
  94344. * Defines an observable called when the optimizer reaches the target frame rate
  94345. */
  94346. this.onSuccessObservable = new BABYLON.Observable();
  94347. /**
  94348. * Defines an observable called when the optimizer enables an optimization
  94349. */
  94350. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  94351. /**
  94352. * Defines an observable called when the optimizer is not able to reach the target frame rate
  94353. */
  94354. this.onFailureObservable = new BABYLON.Observable();
  94355. if (!options) {
  94356. this._options = new SceneOptimizerOptions();
  94357. }
  94358. else {
  94359. this._options = options;
  94360. }
  94361. if (this._options.targetFrameRate) {
  94362. this._targetFrameRate = this._options.targetFrameRate;
  94363. }
  94364. if (this._options.trackerDuration) {
  94365. this._trackerDuration = this._options.trackerDuration;
  94366. }
  94367. if (autoGeneratePriorities) {
  94368. var priority = 0;
  94369. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  94370. var optim = _a[_i];
  94371. optim.priority = priority++;
  94372. }
  94373. }
  94374. this._improvementMode = improvementMode;
  94375. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  94376. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  94377. _this._sceneDisposeObserver = null;
  94378. _this.dispose();
  94379. });
  94380. }
  94381. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  94382. /**
  94383. * Gets a boolean indicating if the optimizer is in improvement mode
  94384. */
  94385. get: function () {
  94386. return this._improvementMode;
  94387. },
  94388. enumerable: true,
  94389. configurable: true
  94390. });
  94391. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  94392. /**
  94393. * Gets the current priority level (0 at start)
  94394. */
  94395. get: function () {
  94396. return this._currentPriorityLevel;
  94397. },
  94398. enumerable: true,
  94399. configurable: true
  94400. });
  94401. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  94402. /**
  94403. * Gets the current frame rate checked by the SceneOptimizer
  94404. */
  94405. get: function () {
  94406. return this._currentFrameRate;
  94407. },
  94408. enumerable: true,
  94409. configurable: true
  94410. });
  94411. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  94412. /**
  94413. * Gets or sets the current target frame rate (60 by default)
  94414. */
  94415. get: function () {
  94416. return this._targetFrameRate;
  94417. },
  94418. /**
  94419. * Gets or sets the current target frame rate (60 by default)
  94420. */
  94421. set: function (value) {
  94422. this._targetFrameRate = value;
  94423. },
  94424. enumerable: true,
  94425. configurable: true
  94426. });
  94427. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  94428. /**
  94429. * Gets or sets the current interval between two checks (every 2000ms by default)
  94430. */
  94431. get: function () {
  94432. return this._trackerDuration;
  94433. },
  94434. /**
  94435. * Gets or sets the current interval between two checks (every 2000ms by default)
  94436. */
  94437. set: function (value) {
  94438. this._trackerDuration = value;
  94439. },
  94440. enumerable: true,
  94441. configurable: true
  94442. });
  94443. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  94444. /**
  94445. * Gets the list of active optimizations
  94446. */
  94447. get: function () {
  94448. return this._options.optimizations;
  94449. },
  94450. enumerable: true,
  94451. configurable: true
  94452. });
  94453. /**
  94454. * Stops the current optimizer
  94455. */
  94456. SceneOptimizer.prototype.stop = function () {
  94457. this._isRunning = false;
  94458. };
  94459. /**
  94460. * Reset the optimizer to initial step (current priority level = 0)
  94461. */
  94462. SceneOptimizer.prototype.reset = function () {
  94463. this._currentPriorityLevel = 0;
  94464. };
  94465. /**
  94466. * Start the optimizer. By default it will try to reach a specific framerate
  94467. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  94468. */
  94469. SceneOptimizer.prototype.start = function () {
  94470. var _this = this;
  94471. if (this._isRunning) {
  94472. return;
  94473. }
  94474. this._isRunning = true;
  94475. // Let's wait for the scene to be ready before running our check
  94476. this._scene.executeWhenReady(function () {
  94477. setTimeout(function () {
  94478. _this._checkCurrentState();
  94479. }, _this._trackerDuration);
  94480. });
  94481. };
  94482. SceneOptimizer.prototype._checkCurrentState = function () {
  94483. var _this = this;
  94484. if (!this._isRunning) {
  94485. return;
  94486. }
  94487. var scene = this._scene;
  94488. var options = this._options;
  94489. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  94490. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  94491. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  94492. this._isRunning = false;
  94493. this.onSuccessObservable.notifyObservers(this);
  94494. return;
  94495. }
  94496. // Apply current level of optimizations
  94497. var allDone = true;
  94498. var noOptimizationApplied = true;
  94499. for (var index = 0; index < options.optimizations.length; index++) {
  94500. var optimization = options.optimizations[index];
  94501. if (optimization.priority === this._currentPriorityLevel) {
  94502. noOptimizationApplied = false;
  94503. allDone = allDone && optimization.apply(scene, this);
  94504. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  94505. }
  94506. }
  94507. // If no optimization was applied, this is a failure :(
  94508. if (noOptimizationApplied) {
  94509. this._isRunning = false;
  94510. this.onFailureObservable.notifyObservers(this);
  94511. return;
  94512. }
  94513. // If all optimizations were done, move to next level
  94514. if (allDone) {
  94515. this._currentPriorityLevel++;
  94516. }
  94517. // Let's the system running for a specific amount of time before checking FPS
  94518. scene.executeWhenReady(function () {
  94519. setTimeout(function () {
  94520. _this._checkCurrentState();
  94521. }, _this._trackerDuration);
  94522. });
  94523. };
  94524. /**
  94525. * Release all resources
  94526. */
  94527. SceneOptimizer.prototype.dispose = function () {
  94528. this.stop();
  94529. this.onSuccessObservable.clear();
  94530. this.onFailureObservable.clear();
  94531. this.onNewOptimizationAppliedObservable.clear();
  94532. if (this._sceneDisposeObserver) {
  94533. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  94534. }
  94535. };
  94536. /**
  94537. * Helper function to create a SceneOptimizer with one single line of code
  94538. * @param scene defines the scene to work on
  94539. * @param options defines the options to use with the SceneOptimizer
  94540. * @param onSuccess defines a callback to call on success
  94541. * @param onFailure defines a callback to call on failure
  94542. * @returns the new SceneOptimizer object
  94543. */
  94544. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  94545. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  94546. if (onSuccess) {
  94547. optimizer.onSuccessObservable.add(function () {
  94548. onSuccess();
  94549. });
  94550. }
  94551. if (onFailure) {
  94552. optimizer.onFailureObservable.add(function () {
  94553. onFailure();
  94554. });
  94555. }
  94556. optimizer.start();
  94557. return optimizer;
  94558. };
  94559. return SceneOptimizer;
  94560. }());
  94561. BABYLON.SceneOptimizer = SceneOptimizer;
  94562. })(BABYLON || (BABYLON = {}));
  94563. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  94564. var BABYLON;
  94565. (function (BABYLON) {
  94566. var OutlineRenderer = /** @class */ (function () {
  94567. function OutlineRenderer(scene) {
  94568. this.zOffset = 1;
  94569. this._scene = scene;
  94570. }
  94571. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  94572. var _this = this;
  94573. if (useOverlay === void 0) { useOverlay = false; }
  94574. var scene = this._scene;
  94575. var engine = this._scene.getEngine();
  94576. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  94577. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  94578. return;
  94579. }
  94580. var mesh = subMesh.getRenderingMesh();
  94581. var material = subMesh.getMaterial();
  94582. if (!material || !scene.activeCamera) {
  94583. return;
  94584. }
  94585. engine.enableEffect(this._effect);
  94586. // Logarithmic depth
  94587. if (material.useLogarithmicDepth) {
  94588. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  94589. }
  94590. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  94591. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  94592. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  94593. // Bones
  94594. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  94595. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  94596. }
  94597. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  94598. // Alpha test
  94599. if (material && material.needAlphaTesting()) {
  94600. var alphaTexture = material.getAlphaTestTexture();
  94601. if (alphaTexture) {
  94602. this._effect.setTexture("diffuseSampler", alphaTexture);
  94603. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  94604. }
  94605. }
  94606. engine.setZOffset(-this.zOffset);
  94607. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  94608. engine.setZOffset(0);
  94609. };
  94610. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  94611. var defines = [];
  94612. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  94613. var mesh = subMesh.getMesh();
  94614. var material = subMesh.getMaterial();
  94615. if (material) {
  94616. // Alpha test
  94617. if (material.needAlphaTesting()) {
  94618. defines.push("#define ALPHATEST");
  94619. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  94620. attribs.push(BABYLON.VertexBuffer.UVKind);
  94621. defines.push("#define UV1");
  94622. }
  94623. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  94624. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  94625. defines.push("#define UV2");
  94626. }
  94627. }
  94628. //Logarithmic depth
  94629. if (material.useLogarithmicDepth) {
  94630. defines.push("#define LOGARITHMICDEPTH");
  94631. }
  94632. }
  94633. // Bones
  94634. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  94635. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  94636. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  94637. if (mesh.numBoneInfluencers > 4) {
  94638. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  94639. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  94640. }
  94641. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  94642. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  94643. }
  94644. else {
  94645. defines.push("#define NUM_BONE_INFLUENCERS 0");
  94646. }
  94647. // Instances
  94648. if (useInstances) {
  94649. defines.push("#define INSTANCES");
  94650. attribs.push("world0");
  94651. attribs.push("world1");
  94652. attribs.push("world2");
  94653. attribs.push("world3");
  94654. }
  94655. // Get correct effect
  94656. var join = defines.join("\n");
  94657. if (this._cachedDefines !== join) {
  94658. this._cachedDefines = join;
  94659. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  94660. }
  94661. return this._effect.isReady();
  94662. };
  94663. return OutlineRenderer;
  94664. }());
  94665. BABYLON.OutlineRenderer = OutlineRenderer;
  94666. })(BABYLON || (BABYLON = {}));
  94667. //# sourceMappingURL=babylon.outlineRenderer.js.map
  94668. var BABYLON;
  94669. (function (BABYLON) {
  94670. var FaceAdjacencies = /** @class */ (function () {
  94671. function FaceAdjacencies() {
  94672. this.edges = new Array();
  94673. this.edgesConnectedCount = 0;
  94674. }
  94675. return FaceAdjacencies;
  94676. }());
  94677. var EdgesRenderer = /** @class */ (function () {
  94678. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  94679. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  94680. if (epsilon === void 0) { epsilon = 0.95; }
  94681. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  94682. this.edgesWidthScalerForOrthographic = 1000.0;
  94683. this.edgesWidthScalerForPerspective = 50.0;
  94684. this._linesPositions = new Array();
  94685. this._linesNormals = new Array();
  94686. this._linesIndices = new Array();
  94687. this._buffers = {};
  94688. this._checkVerticesInsteadOfIndices = false;
  94689. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  94690. this.isEnabled = true;
  94691. this._source = source;
  94692. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  94693. this._epsilon = epsilon;
  94694. this._prepareRessources();
  94695. this._generateEdgesLines();
  94696. }
  94697. EdgesRenderer.prototype._prepareRessources = function () {
  94698. if (this._lineShader) {
  94699. return;
  94700. }
  94701. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  94702. attributes: ["position", "normal"],
  94703. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  94704. });
  94705. this._lineShader.disableDepthWrite = true;
  94706. this._lineShader.backFaceCulling = false;
  94707. };
  94708. EdgesRenderer.prototype._rebuild = function () {
  94709. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  94710. if (buffer) {
  94711. buffer._rebuild();
  94712. }
  94713. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  94714. if (buffer) {
  94715. buffer._rebuild();
  94716. }
  94717. var scene = this._source.getScene();
  94718. var engine = scene.getEngine();
  94719. this._ib = engine.createIndexBuffer(this._linesIndices);
  94720. };
  94721. EdgesRenderer.prototype.dispose = function () {
  94722. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  94723. if (buffer) {
  94724. buffer.dispose();
  94725. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  94726. }
  94727. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  94728. if (buffer) {
  94729. buffer.dispose();
  94730. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  94731. }
  94732. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  94733. this._lineShader.dispose();
  94734. };
  94735. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  94736. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  94737. return 0;
  94738. }
  94739. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  94740. return 1;
  94741. }
  94742. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  94743. return 2;
  94744. }
  94745. return -1;
  94746. };
  94747. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  94748. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  94749. return 0;
  94750. }
  94751. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  94752. return 1;
  94753. }
  94754. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  94755. return 2;
  94756. }
  94757. return -1;
  94758. };
  94759. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  94760. var needToCreateLine;
  94761. if (edge === undefined) {
  94762. needToCreateLine = true;
  94763. }
  94764. else {
  94765. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  94766. needToCreateLine = dotProduct < this._epsilon;
  94767. }
  94768. if (needToCreateLine) {
  94769. var offset = this._linesPositions.length / 3;
  94770. var normal = p0.subtract(p1);
  94771. normal.normalize();
  94772. // Positions
  94773. this._linesPositions.push(p0.x);
  94774. this._linesPositions.push(p0.y);
  94775. this._linesPositions.push(p0.z);
  94776. this._linesPositions.push(p0.x);
  94777. this._linesPositions.push(p0.y);
  94778. this._linesPositions.push(p0.z);
  94779. this._linesPositions.push(p1.x);
  94780. this._linesPositions.push(p1.y);
  94781. this._linesPositions.push(p1.z);
  94782. this._linesPositions.push(p1.x);
  94783. this._linesPositions.push(p1.y);
  94784. this._linesPositions.push(p1.z);
  94785. // Normals
  94786. this._linesNormals.push(p1.x);
  94787. this._linesNormals.push(p1.y);
  94788. this._linesNormals.push(p1.z);
  94789. this._linesNormals.push(-1);
  94790. this._linesNormals.push(p1.x);
  94791. this._linesNormals.push(p1.y);
  94792. this._linesNormals.push(p1.z);
  94793. this._linesNormals.push(1);
  94794. this._linesNormals.push(p0.x);
  94795. this._linesNormals.push(p0.y);
  94796. this._linesNormals.push(p0.z);
  94797. this._linesNormals.push(-1);
  94798. this._linesNormals.push(p0.x);
  94799. this._linesNormals.push(p0.y);
  94800. this._linesNormals.push(p0.z);
  94801. this._linesNormals.push(1);
  94802. // Indices
  94803. this._linesIndices.push(offset);
  94804. this._linesIndices.push(offset + 1);
  94805. this._linesIndices.push(offset + 2);
  94806. this._linesIndices.push(offset);
  94807. this._linesIndices.push(offset + 2);
  94808. this._linesIndices.push(offset + 3);
  94809. }
  94810. };
  94811. EdgesRenderer.prototype._generateEdgesLines = function () {
  94812. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  94813. var indices = this._source.getIndices();
  94814. if (!indices || !positions) {
  94815. return;
  94816. }
  94817. // First let's find adjacencies
  94818. var adjacencies = new Array();
  94819. var faceNormals = new Array();
  94820. var index;
  94821. var faceAdjacencies;
  94822. // Prepare faces
  94823. for (index = 0; index < indices.length; index += 3) {
  94824. faceAdjacencies = new FaceAdjacencies();
  94825. var p0Index = indices[index];
  94826. var p1Index = indices[index + 1];
  94827. var p2Index = indices[index + 2];
  94828. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  94829. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  94830. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  94831. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  94832. faceNormal.normalize();
  94833. faceNormals.push(faceNormal);
  94834. adjacencies.push(faceAdjacencies);
  94835. }
  94836. // Scan
  94837. for (index = 0; index < adjacencies.length; index++) {
  94838. faceAdjacencies = adjacencies[index];
  94839. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  94840. var otherFaceAdjacencies = adjacencies[otherIndex];
  94841. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  94842. break;
  94843. }
  94844. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  94845. continue;
  94846. }
  94847. var otherP0 = indices[otherIndex * 3];
  94848. var otherP1 = indices[otherIndex * 3 + 1];
  94849. var otherP2 = indices[otherIndex * 3 + 2];
  94850. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  94851. var otherEdgeIndex = 0;
  94852. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  94853. continue;
  94854. }
  94855. switch (edgeIndex) {
  94856. case 0:
  94857. if (this._checkVerticesInsteadOfIndices) {
  94858. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  94859. }
  94860. else {
  94861. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  94862. }
  94863. break;
  94864. case 1:
  94865. if (this._checkVerticesInsteadOfIndices) {
  94866. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  94867. }
  94868. else {
  94869. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  94870. }
  94871. break;
  94872. case 2:
  94873. if (this._checkVerticesInsteadOfIndices) {
  94874. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  94875. }
  94876. else {
  94877. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  94878. }
  94879. break;
  94880. }
  94881. if (otherEdgeIndex === -1) {
  94882. continue;
  94883. }
  94884. faceAdjacencies.edges[edgeIndex] = otherIndex;
  94885. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  94886. faceAdjacencies.edgesConnectedCount++;
  94887. otherFaceAdjacencies.edgesConnectedCount++;
  94888. if (faceAdjacencies.edgesConnectedCount === 3) {
  94889. break;
  94890. }
  94891. }
  94892. }
  94893. }
  94894. // Create lines
  94895. for (index = 0; index < adjacencies.length; index++) {
  94896. // 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
  94897. var current = adjacencies[index];
  94898. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  94899. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  94900. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  94901. }
  94902. // Merge into a single mesh
  94903. var engine = this._source.getScene().getEngine();
  94904. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  94905. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  94906. this._ib = engine.createIndexBuffer(this._linesIndices);
  94907. this._indicesCount = this._linesIndices.length;
  94908. };
  94909. EdgesRenderer.prototype.render = function () {
  94910. var scene = this._source.getScene();
  94911. if (!this._lineShader.isReady() || !scene.activeCamera) {
  94912. return;
  94913. }
  94914. var engine = scene.getEngine();
  94915. this._lineShader._preBind();
  94916. // VBOs
  94917. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  94918. scene.resetCachedMaterial();
  94919. this._lineShader.setColor4("color", this._source.edgesColor);
  94920. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  94921. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  94922. }
  94923. else {
  94924. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  94925. }
  94926. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  94927. this._lineShader.bind(this._source.getWorldMatrix());
  94928. // Draw order
  94929. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  94930. this._lineShader.unbind();
  94931. engine.setDepthWrite(true);
  94932. };
  94933. return EdgesRenderer;
  94934. }());
  94935. BABYLON.EdgesRenderer = EdgesRenderer;
  94936. })(BABYLON || (BABYLON = {}));
  94937. //# sourceMappingURL=babylon.edgesRenderer.js.map
  94938. var __assign = (this && this.__assign) || Object.assign || function(t) {
  94939. for (var s, i = 1, n = arguments.length; i < n; i++) {
  94940. s = arguments[i];
  94941. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  94942. t[p] = s[p];
  94943. }
  94944. return t;
  94945. };
  94946. var BABYLON;
  94947. (function (BABYLON) {
  94948. /**
  94949. * The effect layer Helps adding post process effect blended with the main pass.
  94950. *
  94951. * This can be for instance use to generate glow or higlight effects on the scene.
  94952. *
  94953. * The effect layer class can not be used directly and is intented to inherited from to be
  94954. * customized per effects.
  94955. */
  94956. var EffectLayer = /** @class */ (function () {
  94957. /**
  94958. * Instantiates a new effect Layer and references it in the scene.
  94959. * @param name The name of the layer
  94960. * @param scene The scene to use the layer in
  94961. */
  94962. function EffectLayer(
  94963. /** The Friendly of the effect in the scene */
  94964. name, scene) {
  94965. this._vertexBuffers = {};
  94966. this._maxSize = 0;
  94967. this._mainTextureDesiredSize = { width: 0, height: 0 };
  94968. this._shouldRender = true;
  94969. this._postProcesses = [];
  94970. this._textures = [];
  94971. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  94972. /**
  94973. * The clear color of the texture used to generate the glow map.
  94974. */
  94975. this.neutralColor = new BABYLON.Color4();
  94976. /**
  94977. * Specifies wether the highlight layer is enabled or not.
  94978. */
  94979. this.isEnabled = true;
  94980. /**
  94981. * An event triggered when the effect layer has been disposed.
  94982. */
  94983. this.onDisposeObservable = new BABYLON.Observable();
  94984. /**
  94985. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  94986. */
  94987. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  94988. /**
  94989. * An event triggered when the generated texture is being merged in the scene.
  94990. */
  94991. this.onBeforeComposeObservable = new BABYLON.Observable();
  94992. /**
  94993. * An event triggered when the generated texture has been merged in the scene.
  94994. */
  94995. this.onAfterComposeObservable = new BABYLON.Observable();
  94996. /**
  94997. * An event triggered when the efffect layer changes its size.
  94998. */
  94999. this.onSizeChangedObservable = new BABYLON.Observable();
  95000. this.name = name;
  95001. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95002. this._engine = scene.getEngine();
  95003. this._maxSize = this._engine.getCaps().maxTextureSize;
  95004. this._scene.effectLayers.push(this);
  95005. // Generate Buffers
  95006. this._generateIndexBuffer();
  95007. this._genrateVertexBuffer();
  95008. }
  95009. Object.defineProperty(EffectLayer.prototype, "camera", {
  95010. /**
  95011. * Gets the camera attached to the layer.
  95012. */
  95013. get: function () {
  95014. return this._effectLayerOptions.camera;
  95015. },
  95016. enumerable: true,
  95017. configurable: true
  95018. });
  95019. /**
  95020. * Initializes the effect layer with the required options.
  95021. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  95022. */
  95023. EffectLayer.prototype._init = function (options) {
  95024. // Adapt options
  95025. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  95026. this._setMainTextureSize();
  95027. this._createMainTexture();
  95028. this._createTextureAndPostProcesses();
  95029. this._mergeEffect = this._createMergeEffect();
  95030. };
  95031. /**
  95032. * Generates the index buffer of the full screen quad blending to the main canvas.
  95033. */
  95034. EffectLayer.prototype._generateIndexBuffer = function () {
  95035. // Indices
  95036. var indices = [];
  95037. indices.push(0);
  95038. indices.push(1);
  95039. indices.push(2);
  95040. indices.push(0);
  95041. indices.push(2);
  95042. indices.push(3);
  95043. this._indexBuffer = this._engine.createIndexBuffer(indices);
  95044. };
  95045. /**
  95046. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  95047. */
  95048. EffectLayer.prototype._genrateVertexBuffer = function () {
  95049. // VBO
  95050. var vertices = [];
  95051. vertices.push(1, 1);
  95052. vertices.push(-1, 1);
  95053. vertices.push(-1, -1);
  95054. vertices.push(1, -1);
  95055. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  95056. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  95057. };
  95058. /**
  95059. * Sets the main texture desired size which is the closest power of two
  95060. * of the engine canvas size.
  95061. */
  95062. EffectLayer.prototype._setMainTextureSize = function () {
  95063. if (this._effectLayerOptions.mainTextureFixedSize) {
  95064. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  95065. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  95066. }
  95067. else {
  95068. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  95069. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  95070. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  95071. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  95072. }
  95073. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  95074. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  95075. };
  95076. /**
  95077. * Creates the main texture for the effect layer.
  95078. */
  95079. EffectLayer.prototype._createMainTexture = function () {
  95080. var _this = this;
  95081. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  95082. width: this._mainTextureDesiredSize.width,
  95083. height: this._mainTextureDesiredSize.height
  95084. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  95085. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  95086. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95087. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95088. this._mainTexture.anisotropicFilteringLevel = 1;
  95089. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  95090. this._mainTexture.renderParticles = false;
  95091. this._mainTexture.renderList = null;
  95092. this._mainTexture.ignoreCameraViewport = true;
  95093. // Custom render function
  95094. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  95095. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  95096. var index;
  95097. var engine = _this._scene.getEngine();
  95098. if (depthOnlySubMeshes.length) {
  95099. engine.setColorWrite(false);
  95100. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  95101. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  95102. }
  95103. engine.setColorWrite(true);
  95104. }
  95105. for (index = 0; index < opaqueSubMeshes.length; index++) {
  95106. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  95107. }
  95108. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  95109. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  95110. }
  95111. for (index = 0; index < transparentSubMeshes.length; index++) {
  95112. _this._renderSubMesh(transparentSubMeshes.data[index]);
  95113. }
  95114. };
  95115. this._mainTexture.onClearObservable.add(function (engine) {
  95116. engine.clear(_this.neutralColor, true, true, true);
  95117. });
  95118. };
  95119. /**
  95120. * Checks for the readiness of the element composing the layer.
  95121. * @param subMesh the mesh to check for
  95122. * @param useInstances specify wether or not to use instances to render the mesh
  95123. * @param emissiveTexture the associated emissive texture used to generate the glow
  95124. * @return true if ready otherwise, false
  95125. */
  95126. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  95127. var material = subMesh.getMaterial();
  95128. if (!material) {
  95129. return false;
  95130. }
  95131. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  95132. return false;
  95133. }
  95134. var defines = [];
  95135. var attribs = [BABYLON.VertexBuffer.PositionKind];
  95136. var mesh = subMesh.getMesh();
  95137. var uv1 = false;
  95138. var uv2 = false;
  95139. // Alpha test
  95140. if (material && material.needAlphaTesting()) {
  95141. var alphaTexture = material.getAlphaTestTexture();
  95142. if (alphaTexture) {
  95143. defines.push("#define ALPHATEST");
  95144. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  95145. alphaTexture.coordinatesIndex === 1) {
  95146. defines.push("#define DIFFUSEUV2");
  95147. uv2 = true;
  95148. }
  95149. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95150. defines.push("#define DIFFUSEUV1");
  95151. uv1 = true;
  95152. }
  95153. }
  95154. }
  95155. // Emissive
  95156. if (emissiveTexture) {
  95157. defines.push("#define EMISSIVE");
  95158. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  95159. emissiveTexture.coordinatesIndex === 1) {
  95160. defines.push("#define EMISSIVEUV2");
  95161. uv2 = true;
  95162. }
  95163. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95164. defines.push("#define EMISSIVEUV1");
  95165. uv1 = true;
  95166. }
  95167. }
  95168. if (uv1) {
  95169. attribs.push(BABYLON.VertexBuffer.UVKind);
  95170. defines.push("#define UV1");
  95171. }
  95172. if (uv2) {
  95173. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95174. defines.push("#define UV2");
  95175. }
  95176. // Bones
  95177. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  95178. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  95179. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  95180. if (mesh.numBoneInfluencers > 4) {
  95181. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  95182. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  95183. }
  95184. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  95185. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  95186. }
  95187. else {
  95188. defines.push("#define NUM_BONE_INFLUENCERS 0");
  95189. }
  95190. // Morph targets
  95191. var manager = mesh.morphTargetManager;
  95192. var morphInfluencers = 0;
  95193. if (manager) {
  95194. if (manager.numInfluencers > 0) {
  95195. defines.push("#define MORPHTARGETS");
  95196. morphInfluencers = manager.numInfluencers;
  95197. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  95198. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  95199. }
  95200. }
  95201. // Instances
  95202. if (useInstances) {
  95203. defines.push("#define INSTANCES");
  95204. attribs.push("world0");
  95205. attribs.push("world1");
  95206. attribs.push("world2");
  95207. attribs.push("world3");
  95208. }
  95209. // Get correct effect
  95210. var join = defines.join("\n");
  95211. if (this._cachedDefines !== join) {
  95212. this._cachedDefines = join;
  95213. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  95214. }
  95215. return this._effectLayerMapGenerationEffect.isReady();
  95216. };
  95217. /**
  95218. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  95219. */
  95220. EffectLayer.prototype.render = function () {
  95221. var currentEffect = this._mergeEffect;
  95222. // Check
  95223. if (!currentEffect.isReady())
  95224. return;
  95225. for (var i = 0; i < this._postProcesses.length; i++) {
  95226. if (!this._postProcesses[i].isReady()) {
  95227. return;
  95228. }
  95229. }
  95230. var engine = this._scene.getEngine();
  95231. this.onBeforeComposeObservable.notifyObservers(this);
  95232. // Render
  95233. engine.enableEffect(currentEffect);
  95234. engine.setState(false);
  95235. // VBOs
  95236. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  95237. // Cache
  95238. var previousAlphaMode = engine.getAlphaMode();
  95239. // Go Blend.
  95240. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  95241. // Blends the map on the main canvas.
  95242. this._internalRender(currentEffect);
  95243. // Restore Alpha
  95244. engine.setAlphaMode(previousAlphaMode);
  95245. this.onAfterComposeObservable.notifyObservers(this);
  95246. // Handle size changes.
  95247. var size = this._mainTexture.getSize();
  95248. this._setMainTextureSize();
  95249. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  95250. // Recreate RTT and post processes on size change.
  95251. this.onSizeChangedObservable.notifyObservers(this);
  95252. this._disposeTextureAndPostProcesses();
  95253. this._createMainTexture();
  95254. this._createTextureAndPostProcesses();
  95255. }
  95256. };
  95257. /**
  95258. * Determine if a given mesh will be used in the current effect.
  95259. * @param mesh mesh to test
  95260. * @returns true if the mesh will be used
  95261. */
  95262. EffectLayer.prototype.hasMesh = function (mesh) {
  95263. return true;
  95264. };
  95265. /**
  95266. * Returns true if the layer contains information to display, otherwise false.
  95267. * @returns true if the glow layer should be rendered
  95268. */
  95269. EffectLayer.prototype.shouldRender = function () {
  95270. return this.isEnabled && this._shouldRender;
  95271. };
  95272. /**
  95273. * Returns true if the mesh should render, otherwise false.
  95274. * @param mesh The mesh to render
  95275. * @returns true if it should render otherwise false
  95276. */
  95277. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  95278. return true;
  95279. };
  95280. /**
  95281. * Returns true if the mesh should render, otherwise false.
  95282. * @param mesh The mesh to render
  95283. * @returns true if it should render otherwise false
  95284. */
  95285. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  95286. return true;
  95287. };
  95288. /**
  95289. * Renders the submesh passed in parameter to the generation map.
  95290. */
  95291. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  95292. var _this = this;
  95293. if (!this.shouldRender()) {
  95294. return;
  95295. }
  95296. var material = subMesh.getMaterial();
  95297. var mesh = subMesh.getRenderingMesh();
  95298. var scene = this._scene;
  95299. var engine = scene.getEngine();
  95300. if (!material) {
  95301. return;
  95302. }
  95303. // Do not block in blend mode.
  95304. if (material.needAlphaBlendingForMesh(mesh)) {
  95305. return;
  95306. }
  95307. // Culling
  95308. engine.setState(material.backFaceCulling);
  95309. // Managing instances
  95310. var batch = mesh._getInstancesRenderList(subMesh._id);
  95311. if (batch.mustReturn) {
  95312. return;
  95313. }
  95314. // Early Exit per mesh
  95315. if (!this._shouldRenderMesh(mesh)) {
  95316. return;
  95317. }
  95318. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  95319. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  95320. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  95321. engine.enableEffect(this._effectLayerMapGenerationEffect);
  95322. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  95323. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  95324. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  95325. // Alpha test
  95326. if (material && material.needAlphaTesting()) {
  95327. var alphaTexture = material.getAlphaTestTexture();
  95328. if (alphaTexture) {
  95329. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  95330. var textureMatrix = alphaTexture.getTextureMatrix();
  95331. if (textureMatrix) {
  95332. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  95333. }
  95334. }
  95335. }
  95336. // Glow emissive only
  95337. if (this._emissiveTextureAndColor.texture) {
  95338. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  95339. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  95340. }
  95341. // Bones
  95342. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  95343. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  95344. }
  95345. // Morph targets
  95346. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  95347. // Draw
  95348. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  95349. }
  95350. else {
  95351. // Need to reset refresh rate of the shadowMap
  95352. this._mainTexture.resetRefreshCounter();
  95353. }
  95354. };
  95355. /**
  95356. * Rebuild the required buffers.
  95357. * @hidden Internal use only.
  95358. */
  95359. EffectLayer.prototype._rebuild = function () {
  95360. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  95361. if (vb) {
  95362. vb._rebuild();
  95363. }
  95364. this._generateIndexBuffer();
  95365. };
  95366. /**
  95367. * Dispose only the render target textures and post process.
  95368. */
  95369. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  95370. this._mainTexture.dispose();
  95371. for (var i = 0; i < this._postProcesses.length; i++) {
  95372. if (this._postProcesses[i]) {
  95373. this._postProcesses[i].dispose();
  95374. }
  95375. }
  95376. this._postProcesses = [];
  95377. for (var i = 0; i < this._textures.length; i++) {
  95378. if (this._textures[i]) {
  95379. this._textures[i].dispose();
  95380. }
  95381. }
  95382. this._textures = [];
  95383. };
  95384. /**
  95385. * Dispose the highlight layer and free resources.
  95386. */
  95387. EffectLayer.prototype.dispose = function () {
  95388. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  95389. if (vertexBuffer) {
  95390. vertexBuffer.dispose();
  95391. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  95392. }
  95393. if (this._indexBuffer) {
  95394. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  95395. this._indexBuffer = null;
  95396. }
  95397. // Clean textures and post processes
  95398. this._disposeTextureAndPostProcesses();
  95399. // Remove from scene
  95400. var index = this._scene.effectLayers.indexOf(this, 0);
  95401. if (index > -1) {
  95402. this._scene.effectLayers.splice(index, 1);
  95403. }
  95404. // Callback
  95405. this.onDisposeObservable.notifyObservers(this);
  95406. this.onDisposeObservable.clear();
  95407. this.onBeforeRenderMainTextureObservable.clear();
  95408. this.onBeforeComposeObservable.clear();
  95409. this.onAfterComposeObservable.clear();
  95410. this.onSizeChangedObservable.clear();
  95411. };
  95412. /**
  95413. * Gets the class name of the effect layer
  95414. * @returns the string with the class name of the effect layer
  95415. */
  95416. EffectLayer.prototype.getClassName = function () {
  95417. return "EffectLayer";
  95418. };
  95419. /**
  95420. * Creates an effect layer from parsed effect layer data
  95421. * @param parsedEffectLayer defines effect layer data
  95422. * @param scene defines the current scene
  95423. * @param rootUrl defines the root URL containing the effect layer information
  95424. * @returns a parsed effect Layer
  95425. */
  95426. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  95427. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  95428. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  95429. };
  95430. __decorate([
  95431. BABYLON.serialize()
  95432. ], EffectLayer.prototype, "name", void 0);
  95433. __decorate([
  95434. BABYLON.serializeAsColor4()
  95435. ], EffectLayer.prototype, "neutralColor", void 0);
  95436. __decorate([
  95437. BABYLON.serialize()
  95438. ], EffectLayer.prototype, "isEnabled", void 0);
  95439. __decorate([
  95440. BABYLON.serializeAsCameraReference()
  95441. ], EffectLayer.prototype, "camera", null);
  95442. return EffectLayer;
  95443. }());
  95444. BABYLON.EffectLayer = EffectLayer;
  95445. })(BABYLON || (BABYLON = {}));
  95446. //# sourceMappingURL=babylon.effectLayer.js.map
  95447. var BABYLON;
  95448. (function (BABYLON) {
  95449. /**
  95450. * Special Glow Blur post process only blurring the alpha channel
  95451. * It enforces keeping the most luminous color in the color channel.
  95452. */
  95453. var GlowBlurPostProcess = /** @class */ (function (_super) {
  95454. __extends(GlowBlurPostProcess, _super);
  95455. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  95456. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  95457. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  95458. _this.direction = direction;
  95459. _this.kernel = kernel;
  95460. _this.onApplyObservable.add(function (effect) {
  95461. effect.setFloat2("screenSize", _this.width, _this.height);
  95462. effect.setVector2("direction", _this.direction);
  95463. effect.setFloat("blurWidth", _this.kernel);
  95464. });
  95465. return _this;
  95466. }
  95467. return GlowBlurPostProcess;
  95468. }(BABYLON.PostProcess));
  95469. /**
  95470. * The highlight layer Helps adding a glow effect around a mesh.
  95471. *
  95472. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  95473. * glowy meshes to your scene.
  95474. *
  95475. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  95476. */
  95477. var HighlightLayer = /** @class */ (function (_super) {
  95478. __extends(HighlightLayer, _super);
  95479. /**
  95480. * Instantiates a new highlight Layer and references it to the scene..
  95481. * @param name The name of the layer
  95482. * @param scene The scene to use the layer in
  95483. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  95484. */
  95485. function HighlightLayer(name, scene, options) {
  95486. var _this = _super.call(this, name, scene) || this;
  95487. _this.name = name;
  95488. /**
  95489. * Specifies whether or not the inner glow is ACTIVE in the layer.
  95490. */
  95491. _this.innerGlow = true;
  95492. /**
  95493. * Specifies whether or not the outer glow is ACTIVE in the layer.
  95494. */
  95495. _this.outerGlow = true;
  95496. /**
  95497. * An event triggered when the highlight layer is being blurred.
  95498. */
  95499. _this.onBeforeBlurObservable = new BABYLON.Observable();
  95500. /**
  95501. * An event triggered when the highlight layer has been blurred.
  95502. */
  95503. _this.onAfterBlurObservable = new BABYLON.Observable();
  95504. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  95505. _this._meshes = {};
  95506. _this._excludedMeshes = {};
  95507. _this.neutralColor = HighlightLayer.NeutralColor;
  95508. // Warn on stencil
  95509. if (!_this._engine.isStencilEnable) {
  95510. 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 }");
  95511. }
  95512. // Adapt options
  95513. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  95514. // Initialize the layer
  95515. _this._init({
  95516. alphaBlendingMode: _this._options.alphaBlendingMode,
  95517. camera: _this._options.camera,
  95518. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  95519. mainTextureRatio: _this._options.mainTextureRatio
  95520. });
  95521. // Do not render as long as no meshes have been added
  95522. _this._shouldRender = false;
  95523. return _this;
  95524. }
  95525. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  95526. /**
  95527. * Gets the horizontal size of the blur.
  95528. */
  95529. get: function () {
  95530. return this._horizontalBlurPostprocess.kernel;
  95531. },
  95532. /**
  95533. * Specifies the horizontal size of the blur.
  95534. */
  95535. set: function (value) {
  95536. this._horizontalBlurPostprocess.kernel = value;
  95537. },
  95538. enumerable: true,
  95539. configurable: true
  95540. });
  95541. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  95542. /**
  95543. * Gets the vertical size of the blur.
  95544. */
  95545. get: function () {
  95546. return this._verticalBlurPostprocess.kernel;
  95547. },
  95548. /**
  95549. * Specifies the vertical size of the blur.
  95550. */
  95551. set: function (value) {
  95552. this._verticalBlurPostprocess.kernel = value;
  95553. },
  95554. enumerable: true,
  95555. configurable: true
  95556. });
  95557. /**
  95558. * Get the effect name of the layer.
  95559. * @return The effect name
  95560. */
  95561. HighlightLayer.prototype.getEffectName = function () {
  95562. return HighlightLayer.EffectName;
  95563. };
  95564. /**
  95565. * Create the merge effect. This is the shader use to blit the information back
  95566. * to the main canvas at the end of the scene rendering.
  95567. */
  95568. HighlightLayer.prototype._createMergeEffect = function () {
  95569. // Effect
  95570. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  95571. };
  95572. /**
  95573. * Creates the render target textures and post processes used in the highlight layer.
  95574. */
  95575. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  95576. var _this = this;
  95577. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  95578. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  95579. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  95580. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  95581. var textureType = 0;
  95582. if (this._engine.getCaps().textureHalfFloatRender) {
  95583. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95584. }
  95585. else {
  95586. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95587. }
  95588. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  95589. width: blurTextureWidth,
  95590. height: blurTextureHeight
  95591. }, this._scene, false, true, textureType);
  95592. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95593. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95594. this._blurTexture.anisotropicFilteringLevel = 16;
  95595. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  95596. this._blurTexture.renderParticles = false;
  95597. this._blurTexture.ignoreCameraViewport = true;
  95598. this._textures = [this._blurTexture];
  95599. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  95600. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  95601. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  95602. effect.setTexture("textureSampler", _this._mainTexture);
  95603. });
  95604. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  95605. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  95606. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  95607. });
  95608. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  95609. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  95610. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  95611. });
  95612. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  95613. }
  95614. else {
  95615. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  95616. width: blurTextureWidth,
  95617. height: blurTextureHeight
  95618. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95619. this._horizontalBlurPostprocess.width = blurTextureWidth;
  95620. this._horizontalBlurPostprocess.height = blurTextureHeight;
  95621. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  95622. effect.setTexture("textureSampler", _this._mainTexture);
  95623. });
  95624. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  95625. width: blurTextureWidth,
  95626. height: blurTextureHeight
  95627. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95628. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  95629. }
  95630. this._mainTexture.onAfterUnbindObservable.add(function () {
  95631. _this.onBeforeBlurObservable.notifyObservers(_this);
  95632. var internalTexture = _this._blurTexture.getInternalTexture();
  95633. if (internalTexture) {
  95634. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  95635. }
  95636. _this.onAfterBlurObservable.notifyObservers(_this);
  95637. });
  95638. // Prevent autoClear.
  95639. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  95640. };
  95641. /**
  95642. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  95643. */
  95644. HighlightLayer.prototype.needStencil = function () {
  95645. return true;
  95646. };
  95647. /**
  95648. * Checks for the readiness of the element composing the layer.
  95649. * @param subMesh the mesh to check for
  95650. * @param useInstances specify wether or not to use instances to render the mesh
  95651. * @param emissiveTexture the associated emissive texture used to generate the glow
  95652. * @return true if ready otherwise, false
  95653. */
  95654. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  95655. var material = subMesh.getMaterial();
  95656. var mesh = subMesh.getRenderingMesh();
  95657. if (!material || !mesh || !this._meshes) {
  95658. return false;
  95659. }
  95660. var emissiveTexture = null;
  95661. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  95662. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  95663. emissiveTexture = material.emissiveTexture;
  95664. }
  95665. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  95666. };
  95667. /**
  95668. * Implementation specific of rendering the generating effect on the main canvas.
  95669. * @param effect The effect used to render through
  95670. */
  95671. HighlightLayer.prototype._internalRender = function (effect) {
  95672. // Texture
  95673. effect.setTexture("textureSampler", this._blurTexture);
  95674. // Cache
  95675. var engine = this._engine;
  95676. var previousStencilBuffer = engine.getStencilBuffer();
  95677. var previousStencilFunction = engine.getStencilFunction();
  95678. var previousStencilMask = engine.getStencilMask();
  95679. var previousStencilOperationPass = engine.getStencilOperationPass();
  95680. var previousStencilOperationFail = engine.getStencilOperationFail();
  95681. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  95682. var previousStencilReference = engine.getStencilFunctionReference();
  95683. // Stencil operations
  95684. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  95685. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  95686. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  95687. // Draw order
  95688. engine.setStencilMask(0x00);
  95689. engine.setStencilBuffer(true);
  95690. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  95691. // 2 passes inner outer
  95692. if (this.outerGlow) {
  95693. effect.setFloat("offset", 0);
  95694. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  95695. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95696. }
  95697. if (this.innerGlow) {
  95698. effect.setFloat("offset", 1);
  95699. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  95700. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95701. }
  95702. // Restore Cache
  95703. engine.setStencilFunction(previousStencilFunction);
  95704. engine.setStencilMask(previousStencilMask);
  95705. engine.setStencilBuffer(previousStencilBuffer);
  95706. engine.setStencilOperationPass(previousStencilOperationPass);
  95707. engine.setStencilOperationFail(previousStencilOperationFail);
  95708. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  95709. engine.setStencilFunctionReference(previousStencilReference);
  95710. };
  95711. /**
  95712. * Returns true if the layer contains information to display, otherwise false.
  95713. */
  95714. HighlightLayer.prototype.shouldRender = function () {
  95715. if (_super.prototype.shouldRender.call(this)) {
  95716. return this._meshes ? true : false;
  95717. }
  95718. return false;
  95719. };
  95720. /**
  95721. * Returns true if the mesh should render, otherwise false.
  95722. * @param mesh The mesh to render
  95723. * @returns true if it should render otherwise false
  95724. */
  95725. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  95726. // Excluded Mesh
  95727. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  95728. return false;
  95729. }
  95730. ;
  95731. return true;
  95732. };
  95733. /**
  95734. * Sets the required values for both the emissive texture and and the main color.
  95735. */
  95736. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  95737. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  95738. if (highlightLayerMesh) {
  95739. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  95740. }
  95741. else {
  95742. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  95743. }
  95744. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  95745. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  95746. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  95747. }
  95748. else {
  95749. this._emissiveTextureAndColor.texture = null;
  95750. }
  95751. };
  95752. /**
  95753. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  95754. * @param mesh The mesh to exclude from the highlight layer
  95755. */
  95756. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  95757. if (!this._excludedMeshes) {
  95758. return;
  95759. }
  95760. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  95761. if (!meshExcluded) {
  95762. this._excludedMeshes[mesh.uniqueId] = {
  95763. mesh: mesh,
  95764. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  95765. mesh.getEngine().setStencilBuffer(false);
  95766. }),
  95767. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  95768. mesh.getEngine().setStencilBuffer(true);
  95769. }),
  95770. };
  95771. }
  95772. };
  95773. /**
  95774. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  95775. * @param mesh The mesh to highlight
  95776. */
  95777. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  95778. if (!this._excludedMeshes) {
  95779. return;
  95780. }
  95781. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  95782. if (meshExcluded) {
  95783. if (meshExcluded.beforeRender) {
  95784. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  95785. }
  95786. if (meshExcluded.afterRender) {
  95787. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  95788. }
  95789. }
  95790. this._excludedMeshes[mesh.uniqueId] = null;
  95791. };
  95792. /**
  95793. * Determine if a given mesh will be highlighted by the current HighlightLayer
  95794. * @param mesh mesh to test
  95795. * @returns true if the mesh will be highlighted by the current HighlightLayer
  95796. */
  95797. HighlightLayer.prototype.hasMesh = function (mesh) {
  95798. if (!this._meshes) {
  95799. return false;
  95800. }
  95801. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  95802. };
  95803. /**
  95804. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  95805. * @param mesh The mesh to highlight
  95806. * @param color The color of the highlight
  95807. * @param glowEmissiveOnly Extract the glow from the emissive texture
  95808. */
  95809. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  95810. var _this = this;
  95811. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  95812. if (!this._meshes) {
  95813. return;
  95814. }
  95815. var meshHighlight = this._meshes[mesh.uniqueId];
  95816. if (meshHighlight) {
  95817. meshHighlight.color = color;
  95818. }
  95819. else {
  95820. this._meshes[mesh.uniqueId] = {
  95821. mesh: mesh,
  95822. color: color,
  95823. // Lambda required for capture due to Observable this context
  95824. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  95825. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  95826. _this._defaultStencilReference(mesh);
  95827. }
  95828. else {
  95829. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  95830. }
  95831. }),
  95832. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  95833. glowEmissiveOnly: glowEmissiveOnly
  95834. };
  95835. }
  95836. this._shouldRender = true;
  95837. };
  95838. /**
  95839. * Remove a mesh from the highlight layer in order to make it stop glowing.
  95840. * @param mesh The mesh to highlight
  95841. */
  95842. HighlightLayer.prototype.removeMesh = function (mesh) {
  95843. if (!this._meshes) {
  95844. return;
  95845. }
  95846. var meshHighlight = this._meshes[mesh.uniqueId];
  95847. if (meshHighlight) {
  95848. if (meshHighlight.observerHighlight) {
  95849. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  95850. }
  95851. if (meshHighlight.observerDefault) {
  95852. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  95853. }
  95854. delete this._meshes[mesh.uniqueId];
  95855. }
  95856. this._shouldRender = false;
  95857. for (var meshHighlightToCheck in this._meshes) {
  95858. if (this._meshes[meshHighlightToCheck]) {
  95859. this._shouldRender = true;
  95860. break;
  95861. }
  95862. }
  95863. };
  95864. /**
  95865. * Force the stencil to the normal expected value for none glowing parts
  95866. */
  95867. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  95868. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  95869. };
  95870. /**
  95871. * Free any resources and references associated to a mesh.
  95872. * Internal use
  95873. * @param mesh The mesh to free.
  95874. */
  95875. HighlightLayer.prototype._disposeMesh = function (mesh) {
  95876. this.removeMesh(mesh);
  95877. this.removeExcludedMesh(mesh);
  95878. };
  95879. /**
  95880. * Dispose the highlight layer and free resources.
  95881. */
  95882. HighlightLayer.prototype.dispose = function () {
  95883. if (this._meshes) {
  95884. // Clean mesh references
  95885. for (var id in this._meshes) {
  95886. var meshHighlight = this._meshes[id];
  95887. if (meshHighlight && meshHighlight.mesh) {
  95888. if (meshHighlight.observerHighlight) {
  95889. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  95890. }
  95891. if (meshHighlight.observerDefault) {
  95892. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  95893. }
  95894. }
  95895. }
  95896. this._meshes = null;
  95897. }
  95898. if (this._excludedMeshes) {
  95899. for (var id in this._excludedMeshes) {
  95900. var meshHighlight = this._excludedMeshes[id];
  95901. if (meshHighlight) {
  95902. if (meshHighlight.beforeRender) {
  95903. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  95904. }
  95905. if (meshHighlight.afterRender) {
  95906. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  95907. }
  95908. }
  95909. }
  95910. this._excludedMeshes = null;
  95911. }
  95912. _super.prototype.dispose.call(this);
  95913. };
  95914. /**
  95915. * Gets the class name of the effect layer
  95916. * @returns the string with the class name of the effect layer
  95917. */
  95918. HighlightLayer.prototype.getClassName = function () {
  95919. return "HighlightLayer";
  95920. };
  95921. /**
  95922. * Serializes this Highlight layer
  95923. * @returns a serialized Highlight layer object
  95924. */
  95925. HighlightLayer.prototype.serialize = function () {
  95926. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  95927. serializationObject.customType = "BABYLON.HighlightLayer";
  95928. // Highlighted meshes
  95929. serializationObject.meshes = [];
  95930. if (this._meshes) {
  95931. for (var m in this._meshes) {
  95932. var mesh = this._meshes[m];
  95933. if (mesh) {
  95934. serializationObject.meshes.push({
  95935. glowEmissiveOnly: mesh.glowEmissiveOnly,
  95936. color: mesh.color.asArray(),
  95937. meshId: mesh.mesh.id
  95938. });
  95939. }
  95940. }
  95941. }
  95942. // Excluded meshes
  95943. serializationObject.excludedMeshes = [];
  95944. if (this._excludedMeshes) {
  95945. for (var e in this._excludedMeshes) {
  95946. var excludedMesh = this._excludedMeshes[e];
  95947. if (excludedMesh) {
  95948. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  95949. }
  95950. }
  95951. }
  95952. return serializationObject;
  95953. };
  95954. /**
  95955. * Creates a Highlight layer from parsed Highlight layer data
  95956. * @param parsedHightlightLayer defines the Highlight layer data
  95957. * @param scene defines the current scene
  95958. * @param rootUrl defines the root URL containing the Highlight layer information
  95959. * @returns a parsed Highlight layer
  95960. */
  95961. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  95962. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  95963. var index;
  95964. // Excluded meshes
  95965. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  95966. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  95967. if (mesh) {
  95968. hl.addExcludedMesh(mesh);
  95969. }
  95970. }
  95971. // Included meshes
  95972. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  95973. var highlightedMesh = parsedHightlightLayer.meshes[index];
  95974. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  95975. if (mesh) {
  95976. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  95977. }
  95978. }
  95979. return hl;
  95980. };
  95981. /**
  95982. * Effect Name of the highlight layer.
  95983. */
  95984. HighlightLayer.EffectName = "HighlightLayer";
  95985. /**
  95986. * The neutral color used during the preparation of the glow effect.
  95987. * This is black by default as the blend operation is a blend operation.
  95988. */
  95989. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  95990. /**
  95991. * Stencil value used for glowing meshes.
  95992. */
  95993. HighlightLayer.GlowingMeshStencilReference = 0x02;
  95994. /**
  95995. * Stencil value used for the other meshes in the scene.
  95996. */
  95997. HighlightLayer.NormalMeshStencilReference = 0x01;
  95998. __decorate([
  95999. BABYLON.serialize()
  96000. ], HighlightLayer.prototype, "innerGlow", void 0);
  96001. __decorate([
  96002. BABYLON.serialize()
  96003. ], HighlightLayer.prototype, "outerGlow", void 0);
  96004. __decorate([
  96005. BABYLON.serialize()
  96006. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  96007. __decorate([
  96008. BABYLON.serialize()
  96009. ], HighlightLayer.prototype, "blurVerticalSize", null);
  96010. __decorate([
  96011. BABYLON.serialize("options")
  96012. ], HighlightLayer.prototype, "_options", void 0);
  96013. return HighlightLayer;
  96014. }(BABYLON.EffectLayer));
  96015. BABYLON.HighlightLayer = HighlightLayer;
  96016. })(BABYLON || (BABYLON = {}));
  96017. //# sourceMappingURL=babylon.highlightLayer.js.map
  96018. var BABYLON;
  96019. (function (BABYLON) {
  96020. /**
  96021. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  96022. *
  96023. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  96024. * glowy meshes to your scene.
  96025. *
  96026. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  96027. */
  96028. var GlowLayer = /** @class */ (function (_super) {
  96029. __extends(GlowLayer, _super);
  96030. /**
  96031. * Instantiates a new glow Layer and references it to the scene.
  96032. * @param name The name of the layer
  96033. * @param scene The scene to use the layer in
  96034. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  96035. */
  96036. function GlowLayer(name, scene, options) {
  96037. var _this = _super.call(this, name, scene) || this;
  96038. _this._intensity = 1.0;
  96039. _this._includedOnlyMeshes = [];
  96040. _this._excludedMeshes = [];
  96041. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  96042. // Adapt options
  96043. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  96044. // Initialize the layer
  96045. _this._init({
  96046. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  96047. camera: _this._options.camera,
  96048. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  96049. mainTextureRatio: _this._options.mainTextureRatio
  96050. });
  96051. return _this;
  96052. }
  96053. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  96054. /**
  96055. * Gets the kernel size of the blur.
  96056. */
  96057. get: function () {
  96058. return this._horizontalBlurPostprocess1.kernel;
  96059. },
  96060. /**
  96061. * Sets the kernel size of the blur.
  96062. */
  96063. set: function (value) {
  96064. this._horizontalBlurPostprocess1.kernel = value;
  96065. this._verticalBlurPostprocess1.kernel = value;
  96066. this._horizontalBlurPostprocess2.kernel = value;
  96067. this._verticalBlurPostprocess2.kernel = value;
  96068. },
  96069. enumerable: true,
  96070. configurable: true
  96071. });
  96072. Object.defineProperty(GlowLayer.prototype, "intensity", {
  96073. /**
  96074. * Gets the glow intensity.
  96075. */
  96076. get: function () {
  96077. return this._intensity;
  96078. },
  96079. /**
  96080. * Sets the glow intensity.
  96081. */
  96082. set: function (value) {
  96083. this._intensity = value;
  96084. },
  96085. enumerable: true,
  96086. configurable: true
  96087. });
  96088. /**
  96089. * Get the effect name of the layer.
  96090. * @return The effect name
  96091. */
  96092. GlowLayer.prototype.getEffectName = function () {
  96093. return GlowLayer.EffectName;
  96094. };
  96095. /**
  96096. * Create the merge effect. This is the shader use to blit the information back
  96097. * to the main canvas at the end of the scene rendering.
  96098. */
  96099. GlowLayer.prototype._createMergeEffect = function () {
  96100. // Effect
  96101. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  96102. };
  96103. /**
  96104. * Creates the render target textures and post processes used in the glow layer.
  96105. */
  96106. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  96107. var _this = this;
  96108. var blurTextureWidth = this._mainTextureDesiredSize.width;
  96109. var blurTextureHeight = this._mainTextureDesiredSize.height;
  96110. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  96111. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  96112. var textureType = 0;
  96113. if (this._engine.getCaps().textureHalfFloatRender) {
  96114. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  96115. }
  96116. else {
  96117. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96118. }
  96119. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  96120. width: blurTextureWidth,
  96121. height: blurTextureHeight
  96122. }, this._scene, false, true, textureType);
  96123. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96124. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96125. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96126. this._blurTexture1.renderParticles = false;
  96127. this._blurTexture1.ignoreCameraViewport = true;
  96128. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  96129. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  96130. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  96131. width: blurTextureWidth2,
  96132. height: blurTextureHeight2
  96133. }, this._scene, false, true, textureType);
  96134. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96135. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96136. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96137. this._blurTexture2.renderParticles = false;
  96138. this._blurTexture2.ignoreCameraViewport = true;
  96139. this._textures = [this._blurTexture1, this._blurTexture2];
  96140. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  96141. width: blurTextureWidth,
  96142. height: blurTextureHeight
  96143. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96144. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  96145. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  96146. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  96147. effect.setTexture("textureSampler", _this._mainTexture);
  96148. });
  96149. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  96150. width: blurTextureWidth,
  96151. height: blurTextureHeight
  96152. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96153. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  96154. width: blurTextureWidth2,
  96155. height: blurTextureHeight2
  96156. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96157. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  96158. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  96159. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  96160. effect.setTexture("textureSampler", _this._blurTexture1);
  96161. });
  96162. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  96163. width: blurTextureWidth2,
  96164. height: blurTextureHeight2
  96165. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96166. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  96167. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  96168. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  96169. this._mainTexture.samples = this._options.mainTextureSamples;
  96170. this._mainTexture.onAfterUnbindObservable.add(function () {
  96171. var internalTexture = _this._blurTexture1.getInternalTexture();
  96172. if (internalTexture) {
  96173. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  96174. internalTexture = _this._blurTexture2.getInternalTexture();
  96175. if (internalTexture) {
  96176. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  96177. }
  96178. }
  96179. });
  96180. // Prevent autoClear.
  96181. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  96182. };
  96183. /**
  96184. * Checks for the readiness of the element composing the layer.
  96185. * @param subMesh the mesh to check for
  96186. * @param useInstances specify wether or not to use instances to render the mesh
  96187. * @param emissiveTexture the associated emissive texture used to generate the glow
  96188. * @return true if ready otherwise, false
  96189. */
  96190. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  96191. var material = subMesh.getMaterial();
  96192. var mesh = subMesh.getRenderingMesh();
  96193. if (!material || !mesh) {
  96194. return false;
  96195. }
  96196. var emissiveTexture = material.emissiveTexture;
  96197. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  96198. };
  96199. /**
  96200. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  96201. */
  96202. GlowLayer.prototype.needStencil = function () {
  96203. return false;
  96204. };
  96205. /**
  96206. * Implementation specific of rendering the generating effect on the main canvas.
  96207. * @param effect The effect used to render through
  96208. */
  96209. GlowLayer.prototype._internalRender = function (effect) {
  96210. // Texture
  96211. effect.setTexture("textureSampler", this._blurTexture1);
  96212. effect.setTexture("textureSampler2", this._blurTexture2);
  96213. effect.setFloat("offset", this._intensity);
  96214. // Cache
  96215. var engine = this._engine;
  96216. var previousStencilBuffer = engine.getStencilBuffer();
  96217. // Draw order
  96218. engine.setStencilBuffer(false);
  96219. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96220. // Draw order
  96221. engine.setStencilBuffer(previousStencilBuffer);
  96222. };
  96223. /**
  96224. * Sets the required values for both the emissive texture and and the main color.
  96225. */
  96226. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  96227. var textureLevel = 1.0;
  96228. if (this.customEmissiveTextureSelector) {
  96229. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  96230. }
  96231. else {
  96232. if (material) {
  96233. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  96234. if (this._emissiveTextureAndColor.texture) {
  96235. textureLevel = this._emissiveTextureAndColor.texture.level;
  96236. }
  96237. }
  96238. else {
  96239. this._emissiveTextureAndColor.texture = null;
  96240. }
  96241. }
  96242. if (this.customEmissiveColorSelector) {
  96243. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  96244. }
  96245. else {
  96246. if (material.emissiveColor) {
  96247. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  96248. }
  96249. else {
  96250. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  96251. }
  96252. }
  96253. };
  96254. /**
  96255. * Returns true if the mesh should render, otherwise false.
  96256. * @param mesh The mesh to render
  96257. * @returns true if it should render otherwise false
  96258. */
  96259. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  96260. return this.hasMesh(mesh);
  96261. };
  96262. /**
  96263. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  96264. * @param mesh The mesh to exclude from the glow layer
  96265. */
  96266. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  96267. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  96268. this._excludedMeshes.push(mesh.uniqueId);
  96269. }
  96270. };
  96271. /**
  96272. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  96273. * @param mesh The mesh to remove
  96274. */
  96275. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  96276. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  96277. if (index !== -1) {
  96278. this._excludedMeshes.splice(index, 1);
  96279. }
  96280. };
  96281. /**
  96282. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  96283. * @param mesh The mesh to include in the glow layer
  96284. */
  96285. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  96286. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  96287. this._includedOnlyMeshes.push(mesh.uniqueId);
  96288. }
  96289. };
  96290. /**
  96291. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  96292. * @param mesh The mesh to remove
  96293. */
  96294. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  96295. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  96296. if (index !== -1) {
  96297. this._includedOnlyMeshes.splice(index, 1);
  96298. }
  96299. };
  96300. /**
  96301. * Determine if a given mesh will be used in the glow layer
  96302. * @param mesh The mesh to test
  96303. * @returns true if the mesh will be highlighted by the current glow layer
  96304. */
  96305. GlowLayer.prototype.hasMesh = function (mesh) {
  96306. // Included Mesh
  96307. if (this._includedOnlyMeshes.length) {
  96308. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  96309. }
  96310. ;
  96311. // Excluded Mesh
  96312. if (this._excludedMeshes.length) {
  96313. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  96314. }
  96315. ;
  96316. return true;
  96317. };
  96318. /**
  96319. * Free any resources and references associated to a mesh.
  96320. * Internal use
  96321. * @param mesh The mesh to free.
  96322. */
  96323. GlowLayer.prototype._disposeMesh = function (mesh) {
  96324. this.removeIncludedOnlyMesh(mesh);
  96325. this.removeExcludedMesh(mesh);
  96326. };
  96327. /**
  96328. * Gets the class name of the effect layer
  96329. * @returns the string with the class name of the effect layer
  96330. */
  96331. GlowLayer.prototype.getClassName = function () {
  96332. return "GlowLayer";
  96333. };
  96334. /**
  96335. * Serializes this glow layer
  96336. * @returns a serialized glow layer object
  96337. */
  96338. GlowLayer.prototype.serialize = function () {
  96339. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96340. serializationObject.customType = "BABYLON.GlowLayer";
  96341. var index;
  96342. // Included meshes
  96343. serializationObject.includedMeshes = [];
  96344. if (this._includedOnlyMeshes.length) {
  96345. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  96346. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  96347. if (mesh) {
  96348. serializationObject.includedMeshes.push(mesh.id);
  96349. }
  96350. }
  96351. }
  96352. // Excluded meshes
  96353. serializationObject.excludedMeshes = [];
  96354. if (this._excludedMeshes.length) {
  96355. for (index = 0; index < this._excludedMeshes.length; index++) {
  96356. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  96357. if (mesh) {
  96358. serializationObject.excludedMeshes.push(mesh.id);
  96359. }
  96360. }
  96361. }
  96362. return serializationObject;
  96363. };
  96364. /**
  96365. * Creates a Glow Layer from parsed glow layer data
  96366. * @param parsedGlowLayer defines glow layer data
  96367. * @param scene defines the current scene
  96368. * @param rootUrl defines the root URL containing the glow layer information
  96369. * @returns a parsed Glow Layer
  96370. */
  96371. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  96372. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  96373. var index;
  96374. // Excluded meshes
  96375. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  96376. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  96377. if (mesh) {
  96378. gl.addExcludedMesh(mesh);
  96379. }
  96380. }
  96381. // Included meshes
  96382. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  96383. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  96384. if (mesh) {
  96385. gl.addIncludedOnlyMesh(mesh);
  96386. }
  96387. }
  96388. return gl;
  96389. };
  96390. /**
  96391. * Effect Name of the layer.
  96392. */
  96393. GlowLayer.EffectName = "GlowLayer";
  96394. /**
  96395. * The default blur kernel size used for the glow.
  96396. */
  96397. GlowLayer.DefaultBlurKernelSize = 32;
  96398. /**
  96399. * The default texture size ratio used for the glow.
  96400. */
  96401. GlowLayer.DefaultTextureRatio = 0.5;
  96402. __decorate([
  96403. BABYLON.serialize()
  96404. ], GlowLayer.prototype, "blurKernelSize", null);
  96405. __decorate([
  96406. BABYLON.serialize()
  96407. ], GlowLayer.prototype, "intensity", null);
  96408. __decorate([
  96409. BABYLON.serialize("options")
  96410. ], GlowLayer.prototype, "_options", void 0);
  96411. return GlowLayer;
  96412. }(BABYLON.EffectLayer));
  96413. BABYLON.GlowLayer = GlowLayer;
  96414. })(BABYLON || (BABYLON = {}));
  96415. //# sourceMappingURL=babylon.glowLayer.js.map
  96416. var BABYLON;
  96417. (function (BABYLON) {
  96418. /**
  96419. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  96420. */
  96421. var AssetTaskState;
  96422. (function (AssetTaskState) {
  96423. /**
  96424. * Initialization
  96425. */
  96426. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  96427. /**
  96428. * Running
  96429. */
  96430. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  96431. /**
  96432. * Done
  96433. */
  96434. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  96435. /**
  96436. * Error
  96437. */
  96438. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  96439. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  96440. /**
  96441. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  96442. */
  96443. var AbstractAssetTask = /** @class */ (function () {
  96444. /**
  96445. * Creates a new {BABYLON.AssetsManager}
  96446. * @param name defines the name of the task
  96447. */
  96448. function AbstractAssetTask(
  96449. /**
  96450. * Task name
  96451. */ name) {
  96452. this.name = name;
  96453. this._isCompleted = false;
  96454. this._taskState = AssetTaskState.INIT;
  96455. }
  96456. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  96457. /**
  96458. * Get if the task is completed
  96459. */
  96460. get: function () {
  96461. return this._isCompleted;
  96462. },
  96463. enumerable: true,
  96464. configurable: true
  96465. });
  96466. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  96467. /**
  96468. * Gets the current state of the task
  96469. */
  96470. get: function () {
  96471. return this._taskState;
  96472. },
  96473. enumerable: true,
  96474. configurable: true
  96475. });
  96476. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  96477. /**
  96478. * Gets the current error object (if task is in error)
  96479. */
  96480. get: function () {
  96481. return this._errorObject;
  96482. },
  96483. enumerable: true,
  96484. configurable: true
  96485. });
  96486. /**
  96487. * Internal only
  96488. * @hidden
  96489. */
  96490. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  96491. if (this._errorObject) {
  96492. return;
  96493. }
  96494. this._errorObject = {
  96495. message: message,
  96496. exception: exception
  96497. };
  96498. };
  96499. /**
  96500. * Execute the current task
  96501. * @param scene defines the scene where you want your assets to be loaded
  96502. * @param onSuccess is a callback called when the task is successfully executed
  96503. * @param onError is a callback called if an error occurs
  96504. */
  96505. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  96506. var _this = this;
  96507. this._taskState = AssetTaskState.RUNNING;
  96508. this.runTask(scene, function () {
  96509. _this.onDoneCallback(onSuccess, onError);
  96510. }, function (msg, exception) {
  96511. _this.onErrorCallback(onError, msg, exception);
  96512. });
  96513. };
  96514. /**
  96515. * Execute the current task
  96516. * @param scene defines the scene where you want your assets to be loaded
  96517. * @param onSuccess is a callback called when the task is successfully executed
  96518. * @param onError is a callback called if an error occurs
  96519. */
  96520. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96521. throw new Error("runTask is not implemented");
  96522. };
  96523. /**
  96524. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  96525. * This can be used with failed tasks that have the reason for failure fixed.
  96526. */
  96527. AbstractAssetTask.prototype.reset = function () {
  96528. this._taskState = AssetTaskState.INIT;
  96529. };
  96530. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  96531. this._taskState = AssetTaskState.ERROR;
  96532. this._errorObject = {
  96533. message: message,
  96534. exception: exception
  96535. };
  96536. if (this.onError) {
  96537. this.onError(this, message, exception);
  96538. }
  96539. onError();
  96540. };
  96541. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  96542. try {
  96543. this._taskState = AssetTaskState.DONE;
  96544. this._isCompleted = true;
  96545. if (this.onSuccess) {
  96546. this.onSuccess(this);
  96547. }
  96548. onSuccess();
  96549. }
  96550. catch (e) {
  96551. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  96552. }
  96553. };
  96554. return AbstractAssetTask;
  96555. }());
  96556. BABYLON.AbstractAssetTask = AbstractAssetTask;
  96557. /**
  96558. * Class used to share progress information about assets loading
  96559. */
  96560. var AssetsProgressEvent = /** @class */ (function () {
  96561. /**
  96562. * Creates a {BABYLON.AssetsProgressEvent}
  96563. * @param remainingCount defines the number of remaining tasks to process
  96564. * @param totalCount defines the total number of tasks
  96565. * @param task defines the task that was just processed
  96566. */
  96567. function AssetsProgressEvent(remainingCount, totalCount, task) {
  96568. this.remainingCount = remainingCount;
  96569. this.totalCount = totalCount;
  96570. this.task = task;
  96571. }
  96572. return AssetsProgressEvent;
  96573. }());
  96574. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  96575. /**
  96576. * Define a task used by {BABYLON.AssetsManager} to load meshes
  96577. */
  96578. var MeshAssetTask = /** @class */ (function (_super) {
  96579. __extends(MeshAssetTask, _super);
  96580. /**
  96581. * Creates a new {BABYLON.MeshAssetTask}
  96582. * @param name defines the name of the task
  96583. * @param meshesNames defines the list of mesh's names you want to load
  96584. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  96585. * @param sceneFilename defines the filename of the scene to load from
  96586. */
  96587. function MeshAssetTask(
  96588. /**
  96589. * Defines the name of the task
  96590. */
  96591. name,
  96592. /**
  96593. * Defines the list of mesh's names you want to load
  96594. */
  96595. meshesNames,
  96596. /**
  96597. * Defines the root url to use as a base to load your meshes and associated resources
  96598. */
  96599. rootUrl,
  96600. /**
  96601. * Defines the filename of the scene to load from
  96602. */
  96603. sceneFilename) {
  96604. var _this = _super.call(this, name) || this;
  96605. _this.name = name;
  96606. _this.meshesNames = meshesNames;
  96607. _this.rootUrl = rootUrl;
  96608. _this.sceneFilename = sceneFilename;
  96609. return _this;
  96610. }
  96611. /**
  96612. * Execute the current task
  96613. * @param scene defines the scene where you want your assets to be loaded
  96614. * @param onSuccess is a callback called when the task is successfully executed
  96615. * @param onError is a callback called if an error occurs
  96616. */
  96617. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96618. var _this = this;
  96619. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  96620. _this.loadedMeshes = meshes;
  96621. _this.loadedParticleSystems = particleSystems;
  96622. _this.loadedSkeletons = skeletons;
  96623. onSuccess();
  96624. }, null, function (scene, message, exception) {
  96625. onError(message, exception);
  96626. });
  96627. };
  96628. return MeshAssetTask;
  96629. }(AbstractAssetTask));
  96630. BABYLON.MeshAssetTask = MeshAssetTask;
  96631. /**
  96632. * Define a task used by {BABYLON.AssetsManager} to load text content
  96633. */
  96634. var TextFileAssetTask = /** @class */ (function (_super) {
  96635. __extends(TextFileAssetTask, _super);
  96636. /**
  96637. * Creates a new TextFileAssetTask object
  96638. * @param name defines the name of the task
  96639. * @param url defines the location of the file to load
  96640. */
  96641. function TextFileAssetTask(
  96642. /**
  96643. * Defines the name of the task
  96644. */
  96645. name,
  96646. /**
  96647. * Defines the location of the file to load
  96648. */
  96649. url) {
  96650. var _this = _super.call(this, name) || this;
  96651. _this.name = name;
  96652. _this.url = url;
  96653. return _this;
  96654. }
  96655. /**
  96656. * Execute the current task
  96657. * @param scene defines the scene where you want your assets to be loaded
  96658. * @param onSuccess is a callback called when the task is successfully executed
  96659. * @param onError is a callback called if an error occurs
  96660. */
  96661. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96662. var _this = this;
  96663. scene._loadFile(this.url, function (data) {
  96664. _this.text = data;
  96665. onSuccess();
  96666. }, undefined, false, false, function (request, exception) {
  96667. if (request) {
  96668. onError(request.status + " " + request.statusText, exception);
  96669. }
  96670. });
  96671. };
  96672. return TextFileAssetTask;
  96673. }(AbstractAssetTask));
  96674. BABYLON.TextFileAssetTask = TextFileAssetTask;
  96675. /**
  96676. * Define a task used by {BABYLON.AssetsManager} to load binary data
  96677. */
  96678. var BinaryFileAssetTask = /** @class */ (function (_super) {
  96679. __extends(BinaryFileAssetTask, _super);
  96680. /**
  96681. * Creates a new BinaryFileAssetTask object
  96682. * @param name defines the name of the new task
  96683. * @param url defines the location of the file to load
  96684. */
  96685. function BinaryFileAssetTask(
  96686. /**
  96687. * Defines the name of the task
  96688. */
  96689. name,
  96690. /**
  96691. * Defines the location of the file to load
  96692. */
  96693. url) {
  96694. var _this = _super.call(this, name) || this;
  96695. _this.name = name;
  96696. _this.url = url;
  96697. return _this;
  96698. }
  96699. /**
  96700. * Execute the current task
  96701. * @param scene defines the scene where you want your assets to be loaded
  96702. * @param onSuccess is a callback called when the task is successfully executed
  96703. * @param onError is a callback called if an error occurs
  96704. */
  96705. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96706. var _this = this;
  96707. scene._loadFile(this.url, function (data) {
  96708. _this.data = data;
  96709. onSuccess();
  96710. }, undefined, true, true, function (request, exception) {
  96711. if (request) {
  96712. onError(request.status + " " + request.statusText, exception);
  96713. }
  96714. });
  96715. };
  96716. return BinaryFileAssetTask;
  96717. }(AbstractAssetTask));
  96718. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  96719. /**
  96720. * Define a task used by {BABYLON.AssetsManager} to load images
  96721. */
  96722. var ImageAssetTask = /** @class */ (function (_super) {
  96723. __extends(ImageAssetTask, _super);
  96724. /**
  96725. * Creates a new ImageAssetTask
  96726. * @param name defines the name of the task
  96727. * @param url defines the location of the image to load
  96728. */
  96729. function ImageAssetTask(
  96730. /**
  96731. * Defines the name of the task
  96732. */
  96733. name,
  96734. /**
  96735. * Defines the location of the image to load
  96736. */
  96737. url) {
  96738. var _this = _super.call(this, name) || this;
  96739. _this.name = name;
  96740. _this.url = url;
  96741. return _this;
  96742. }
  96743. /**
  96744. * Execute the current task
  96745. * @param scene defines the scene where you want your assets to be loaded
  96746. * @param onSuccess is a callback called when the task is successfully executed
  96747. * @param onError is a callback called if an error occurs
  96748. */
  96749. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96750. var _this = this;
  96751. var img = new Image();
  96752. BABYLON.Tools.SetCorsBehavior(this.url, img);
  96753. img.onload = function () {
  96754. _this.image = img;
  96755. onSuccess();
  96756. };
  96757. img.onerror = function (err) {
  96758. onError("Error loading image", err);
  96759. };
  96760. img.src = this.url;
  96761. };
  96762. return ImageAssetTask;
  96763. }(AbstractAssetTask));
  96764. BABYLON.ImageAssetTask = ImageAssetTask;
  96765. /**
  96766. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  96767. */
  96768. var TextureAssetTask = /** @class */ (function (_super) {
  96769. __extends(TextureAssetTask, _super);
  96770. /**
  96771. * Creates a new TextureAssetTask object
  96772. * @param name defines the name of the task
  96773. * @param url defines the location of the file to load
  96774. * @param noMipmap defines if mipmap should not be generated (default is false)
  96775. * @param invertY defines if texture must be inverted on Y axis (default is false)
  96776. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  96777. */
  96778. function TextureAssetTask(
  96779. /**
  96780. * Defines the name of the task
  96781. */
  96782. name,
  96783. /**
  96784. * Defines the location of the file to load
  96785. */
  96786. url,
  96787. /**
  96788. * Defines if mipmap should not be generated (default is false)
  96789. */
  96790. noMipmap,
  96791. /**
  96792. * Defines if texture must be inverted on Y axis (default is false)
  96793. */
  96794. invertY,
  96795. /**
  96796. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  96797. */
  96798. samplingMode) {
  96799. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  96800. var _this = _super.call(this, name) || this;
  96801. _this.name = name;
  96802. _this.url = url;
  96803. _this.noMipmap = noMipmap;
  96804. _this.invertY = invertY;
  96805. _this.samplingMode = samplingMode;
  96806. return _this;
  96807. }
  96808. /**
  96809. * Execute the current task
  96810. * @param scene defines the scene where you want your assets to be loaded
  96811. * @param onSuccess is a callback called when the task is successfully executed
  96812. * @param onError is a callback called if an error occurs
  96813. */
  96814. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96815. var onload = function () {
  96816. onSuccess();
  96817. };
  96818. var onerror = function (message, exception) {
  96819. onError(message, exception);
  96820. };
  96821. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  96822. };
  96823. return TextureAssetTask;
  96824. }(AbstractAssetTask));
  96825. BABYLON.TextureAssetTask = TextureAssetTask;
  96826. /**
  96827. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  96828. */
  96829. var CubeTextureAssetTask = /** @class */ (function (_super) {
  96830. __extends(CubeTextureAssetTask, _super);
  96831. /**
  96832. * Creates a new CubeTextureAssetTask
  96833. * @param name defines the name of the task
  96834. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  96835. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  96836. * @param noMipmap defines if mipmaps should not be generated (default is false)
  96837. * @param files defines the explicit list of files (undefined by default)
  96838. */
  96839. function CubeTextureAssetTask(
  96840. /**
  96841. * Defines the name of the task
  96842. */
  96843. name,
  96844. /**
  96845. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  96846. */
  96847. url,
  96848. /**
  96849. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  96850. */
  96851. extensions,
  96852. /**
  96853. * Defines if mipmaps should not be generated (default is false)
  96854. */
  96855. noMipmap,
  96856. /**
  96857. * Defines the explicit list of files (undefined by default)
  96858. */
  96859. files) {
  96860. var _this = _super.call(this, name) || this;
  96861. _this.name = name;
  96862. _this.url = url;
  96863. _this.extensions = extensions;
  96864. _this.noMipmap = noMipmap;
  96865. _this.files = files;
  96866. return _this;
  96867. }
  96868. /**
  96869. * Execute the current task
  96870. * @param scene defines the scene where you want your assets to be loaded
  96871. * @param onSuccess is a callback called when the task is successfully executed
  96872. * @param onError is a callback called if an error occurs
  96873. */
  96874. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96875. var onload = function () {
  96876. onSuccess();
  96877. };
  96878. var onerror = function (message, exception) {
  96879. onError(message, exception);
  96880. };
  96881. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  96882. };
  96883. return CubeTextureAssetTask;
  96884. }(AbstractAssetTask));
  96885. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  96886. /**
  96887. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  96888. */
  96889. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  96890. __extends(HDRCubeTextureAssetTask, _super);
  96891. /**
  96892. * Creates a new HDRCubeTextureAssetTask object
  96893. * @param name defines the name of the task
  96894. * @param url defines the location of the file to load
  96895. * @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.
  96896. * @param noMipmap defines if mipmaps should not be generated (default is false)
  96897. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  96898. * @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)
  96899. * @param reserved Internal use only
  96900. */
  96901. function HDRCubeTextureAssetTask(
  96902. /**
  96903. * Defines the name of the task
  96904. */
  96905. name,
  96906. /**
  96907. * Defines the location of the file to load
  96908. */
  96909. url,
  96910. /**
  96911. * Defines the desired size (the more it increases the longer the generation will be)
  96912. */
  96913. size,
  96914. /**
  96915. * Defines if mipmaps should not be generated (default is false)
  96916. */
  96917. noMipmap,
  96918. /**
  96919. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  96920. */
  96921. generateHarmonics,
  96922. /**
  96923. * 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)
  96924. */
  96925. gammaSpace,
  96926. /**
  96927. * Internal Use Only
  96928. */
  96929. reserved) {
  96930. if (noMipmap === void 0) { noMipmap = false; }
  96931. if (generateHarmonics === void 0) { generateHarmonics = true; }
  96932. if (gammaSpace === void 0) { gammaSpace = false; }
  96933. if (reserved === void 0) { reserved = false; }
  96934. var _this = _super.call(this, name) || this;
  96935. _this.name = name;
  96936. _this.url = url;
  96937. _this.size = size;
  96938. _this.noMipmap = noMipmap;
  96939. _this.generateHarmonics = generateHarmonics;
  96940. _this.gammaSpace = gammaSpace;
  96941. _this.reserved = reserved;
  96942. return _this;
  96943. }
  96944. /**
  96945. * Execute the current task
  96946. * @param scene defines the scene where you want your assets to be loaded
  96947. * @param onSuccess is a callback called when the task is successfully executed
  96948. * @param onError is a callback called if an error occurs
  96949. */
  96950. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  96951. var onload = function () {
  96952. onSuccess();
  96953. };
  96954. var onerror = function (message, exception) {
  96955. onError(message, exception);
  96956. };
  96957. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  96958. };
  96959. return HDRCubeTextureAssetTask;
  96960. }(AbstractAssetTask));
  96961. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  96962. /**
  96963. * This class can be used to easily import assets into a scene
  96964. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  96965. */
  96966. var AssetsManager = /** @class */ (function () {
  96967. /**
  96968. * Creates a new AssetsManager
  96969. * @param scene defines the scene to work on
  96970. */
  96971. function AssetsManager(scene) {
  96972. this._isLoading = false;
  96973. this._tasks = new Array();
  96974. this._waitingTasksCount = 0;
  96975. this._totalTasksCount = 0;
  96976. /**
  96977. * Observable called when all tasks are processed
  96978. */
  96979. this.onTaskSuccessObservable = new BABYLON.Observable();
  96980. /**
  96981. * Observable called when a task had an error
  96982. */
  96983. this.onTaskErrorObservable = new BABYLON.Observable();
  96984. /**
  96985. * Observable called when a task is successful
  96986. */
  96987. this.onTasksDoneObservable = new BABYLON.Observable();
  96988. /**
  96989. * Observable called when a task is done (whatever the result is)
  96990. */
  96991. this.onProgressObservable = new BABYLON.Observable();
  96992. /**
  96993. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  96994. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  96995. */
  96996. this.useDefaultLoadingScreen = true;
  96997. this._scene = scene;
  96998. }
  96999. /**
  97000. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  97001. * @param taskName defines the name of the new task
  97002. * @param meshesNames defines the name of meshes to load
  97003. * @param rootUrl defines the root url to use to locate files
  97004. * @param sceneFilename defines the filename of the scene file
  97005. * @returns a new {BABYLON.MeshAssetTask} object
  97006. */
  97007. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  97008. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  97009. this._tasks.push(task);
  97010. return task;
  97011. };
  97012. /**
  97013. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  97014. * @param taskName defines the name of the new task
  97015. * @param url defines the url of the file to load
  97016. * @returns a new {BABYLON.TextFileAssetTask} object
  97017. */
  97018. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  97019. var task = new TextFileAssetTask(taskName, url);
  97020. this._tasks.push(task);
  97021. return task;
  97022. };
  97023. /**
  97024. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  97025. * @param taskName defines the name of the new task
  97026. * @param url defines the url of the file to load
  97027. * @returns a new {BABYLON.BinaryFileAssetTask} object
  97028. */
  97029. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  97030. var task = new BinaryFileAssetTask(taskName, url);
  97031. this._tasks.push(task);
  97032. return task;
  97033. };
  97034. /**
  97035. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  97036. * @param taskName defines the name of the new task
  97037. * @param url defines the url of the file to load
  97038. * @returns a new {BABYLON.ImageAssetTask} object
  97039. */
  97040. AssetsManager.prototype.addImageTask = function (taskName, url) {
  97041. var task = new ImageAssetTask(taskName, url);
  97042. this._tasks.push(task);
  97043. return task;
  97044. };
  97045. /**
  97046. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  97047. * @param taskName defines the name of the new task
  97048. * @param url defines the url of the file to load
  97049. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  97050. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  97051. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  97052. * @returns a new {BABYLON.TextureAssetTask} object
  97053. */
  97054. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  97055. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  97056. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  97057. this._tasks.push(task);
  97058. return task;
  97059. };
  97060. /**
  97061. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  97062. * @param taskName defines the name of the new task
  97063. * @param url defines the url of the file to load
  97064. * @param extensions defines the extension to use to load the cube map (can be null)
  97065. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  97066. * @param files defines the list of files to load (can be null)
  97067. * @returns a new {BABYLON.CubeTextureAssetTask} object
  97068. */
  97069. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  97070. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  97071. this._tasks.push(task);
  97072. return task;
  97073. };
  97074. /**
  97075. *
  97076. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  97077. * @param taskName defines the name of the new task
  97078. * @param url defines the url of the file to load
  97079. * @param size defines the size you want for the cubemap (can be null)
  97080. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  97081. * @param generateHarmonics defines if you want to automatically generate (true by default)
  97082. * @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)
  97083. * @param reserved Internal use only
  97084. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  97085. */
  97086. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  97087. if (noMipmap === void 0) { noMipmap = false; }
  97088. if (generateHarmonics === void 0) { generateHarmonics = true; }
  97089. if (gammaSpace === void 0) { gammaSpace = false; }
  97090. if (reserved === void 0) { reserved = false; }
  97091. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  97092. this._tasks.push(task);
  97093. return task;
  97094. };
  97095. /**
  97096. * Remove a task from the assets manager.
  97097. * @param task the task to remove
  97098. */
  97099. AssetsManager.prototype.removeTask = function (task) {
  97100. var index = this._tasks.indexOf(task);
  97101. if (index > -1) {
  97102. this._tasks.splice(index, 1);
  97103. }
  97104. };
  97105. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  97106. this._waitingTasksCount--;
  97107. try {
  97108. if (this.onProgress) {
  97109. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  97110. }
  97111. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  97112. }
  97113. catch (e) {
  97114. BABYLON.Tools.Error("Error running progress callbacks.");
  97115. console.log(e);
  97116. }
  97117. if (this._waitingTasksCount === 0) {
  97118. try {
  97119. if (this.onFinish) {
  97120. this.onFinish(this._tasks);
  97121. }
  97122. // Let's remove successfull tasks
  97123. var currentTasks = this._tasks.slice();
  97124. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  97125. var task = currentTasks_1[_i];
  97126. if (task.taskState === AssetTaskState.DONE) {
  97127. var index = this._tasks.indexOf(task);
  97128. if (index > -1) {
  97129. this._tasks.splice(index, 1);
  97130. }
  97131. }
  97132. }
  97133. this.onTasksDoneObservable.notifyObservers(this._tasks);
  97134. }
  97135. catch (e) {
  97136. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  97137. console.log(e);
  97138. }
  97139. this._isLoading = false;
  97140. this._scene.getEngine().hideLoadingUI();
  97141. }
  97142. };
  97143. AssetsManager.prototype._runTask = function (task) {
  97144. var _this = this;
  97145. var done = function () {
  97146. try {
  97147. if (_this.onTaskSuccess) {
  97148. _this.onTaskSuccess(task);
  97149. }
  97150. _this.onTaskSuccessObservable.notifyObservers(task);
  97151. _this._decreaseWaitingTasksCount(task);
  97152. }
  97153. catch (e) {
  97154. error("Error executing task success callbacks", e);
  97155. }
  97156. };
  97157. var error = function (message, exception) {
  97158. task._setErrorObject(message, exception);
  97159. if (_this.onTaskError) {
  97160. _this.onTaskError(task);
  97161. }
  97162. _this.onTaskErrorObservable.notifyObservers(task);
  97163. _this._decreaseWaitingTasksCount(task);
  97164. };
  97165. task.run(this._scene, done, error);
  97166. };
  97167. /**
  97168. * Reset the {BABYLON.AssetsManager} and remove all tasks
  97169. * @return the current instance of the {BABYLON.AssetsManager}
  97170. */
  97171. AssetsManager.prototype.reset = function () {
  97172. this._isLoading = false;
  97173. this._tasks = new Array();
  97174. return this;
  97175. };
  97176. /**
  97177. * Start the loading process
  97178. * @return the current instance of the {BABYLON.AssetsManager}
  97179. */
  97180. AssetsManager.prototype.load = function () {
  97181. if (this._isLoading) {
  97182. return this;
  97183. }
  97184. this._isLoading = true;
  97185. this._waitingTasksCount = this._tasks.length;
  97186. this._totalTasksCount = this._tasks.length;
  97187. if (this._waitingTasksCount === 0) {
  97188. this._isLoading = false;
  97189. if (this.onFinish) {
  97190. this.onFinish(this._tasks);
  97191. }
  97192. this.onTasksDoneObservable.notifyObservers(this._tasks);
  97193. return this;
  97194. }
  97195. if (this.useDefaultLoadingScreen) {
  97196. this._scene.getEngine().displayLoadingUI();
  97197. }
  97198. for (var index = 0; index < this._tasks.length; index++) {
  97199. var task = this._tasks[index];
  97200. if (task.taskState === AssetTaskState.INIT) {
  97201. this._runTask(task);
  97202. }
  97203. }
  97204. return this;
  97205. };
  97206. return AssetsManager;
  97207. }());
  97208. BABYLON.AssetsManager = AssetsManager;
  97209. })(BABYLON || (BABYLON = {}));
  97210. //# sourceMappingURL=babylon.assetsManager.js.map
  97211. var BABYLON;
  97212. (function (BABYLON) {
  97213. var serializedGeometries = [];
  97214. var serializeGeometry = function (geometry, serializationGeometries) {
  97215. if (serializedGeometries[geometry.id]) {
  97216. return;
  97217. }
  97218. if (geometry.doNotSerialize) {
  97219. return;
  97220. }
  97221. if (geometry instanceof BABYLON.BoxGeometry) {
  97222. serializationGeometries.boxes.push(geometry.serialize());
  97223. }
  97224. else if (geometry instanceof BABYLON.SphereGeometry) {
  97225. serializationGeometries.spheres.push(geometry.serialize());
  97226. }
  97227. else if (geometry instanceof BABYLON.CylinderGeometry) {
  97228. serializationGeometries.cylinders.push(geometry.serialize());
  97229. }
  97230. else if (geometry instanceof BABYLON.TorusGeometry) {
  97231. serializationGeometries.toruses.push(geometry.serialize());
  97232. }
  97233. else if (geometry instanceof BABYLON.GroundGeometry) {
  97234. serializationGeometries.grounds.push(geometry.serialize());
  97235. }
  97236. else if (geometry instanceof BABYLON.Plane) {
  97237. serializationGeometries.planes.push(geometry.serialize());
  97238. }
  97239. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  97240. serializationGeometries.torusKnots.push(geometry.serialize());
  97241. }
  97242. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  97243. throw new Error("Unknown primitive type");
  97244. }
  97245. else {
  97246. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  97247. }
  97248. serializedGeometries[geometry.id] = true;
  97249. };
  97250. var serializeMesh = function (mesh, serializationScene) {
  97251. var serializationObject = {};
  97252. // Geometry
  97253. var geometry = mesh._geometry;
  97254. if (geometry) {
  97255. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  97256. // 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
  97257. serializeGeometry(geometry, serializationScene.geometries);
  97258. }
  97259. }
  97260. // Custom
  97261. if (mesh.serialize) {
  97262. mesh.serialize(serializationObject);
  97263. }
  97264. return serializationObject;
  97265. };
  97266. var finalizeSingleMesh = function (mesh, serializationObject) {
  97267. //only works if the mesh is already loaded
  97268. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  97269. //serialize material
  97270. if (mesh.material) {
  97271. if (mesh.material instanceof BABYLON.MultiMaterial) {
  97272. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  97273. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  97274. serializationObject.multiMaterials.push(mesh.material.serialize());
  97275. }
  97276. }
  97277. else {
  97278. serializationObject.materials = serializationObject.materials || [];
  97279. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  97280. serializationObject.materials.push(mesh.material.serialize());
  97281. }
  97282. }
  97283. }
  97284. //serialize geometry
  97285. var geometry = mesh._geometry;
  97286. if (geometry) {
  97287. if (!serializationObject.geometries) {
  97288. serializationObject.geometries = {};
  97289. serializationObject.geometries.boxes = [];
  97290. serializationObject.geometries.spheres = [];
  97291. serializationObject.geometries.cylinders = [];
  97292. serializationObject.geometries.toruses = [];
  97293. serializationObject.geometries.grounds = [];
  97294. serializationObject.geometries.planes = [];
  97295. serializationObject.geometries.torusKnots = [];
  97296. serializationObject.geometries.vertexData = [];
  97297. }
  97298. serializeGeometry(geometry, serializationObject.geometries);
  97299. }
  97300. // Skeletons
  97301. if (mesh.skeleton) {
  97302. serializationObject.skeletons = serializationObject.skeletons || [];
  97303. serializationObject.skeletons.push(mesh.skeleton.serialize());
  97304. }
  97305. //serialize the actual mesh
  97306. serializationObject.meshes = serializationObject.meshes || [];
  97307. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  97308. }
  97309. };
  97310. var SceneSerializer = /** @class */ (function () {
  97311. function SceneSerializer() {
  97312. }
  97313. SceneSerializer.ClearCache = function () {
  97314. serializedGeometries = [];
  97315. };
  97316. SceneSerializer.Serialize = function (scene) {
  97317. var serializationObject = {};
  97318. SceneSerializer.ClearCache();
  97319. // Scene
  97320. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  97321. serializationObject.autoClear = scene.autoClear;
  97322. serializationObject.clearColor = scene.clearColor.asArray();
  97323. serializationObject.ambientColor = scene.ambientColor.asArray();
  97324. serializationObject.gravity = scene.gravity.asArray();
  97325. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  97326. serializationObject.workerCollisions = scene.workerCollisions;
  97327. // Fog
  97328. if (scene.fogMode && scene.fogMode !== 0) {
  97329. serializationObject.fogMode = scene.fogMode;
  97330. serializationObject.fogColor = scene.fogColor.asArray();
  97331. serializationObject.fogStart = scene.fogStart;
  97332. serializationObject.fogEnd = scene.fogEnd;
  97333. serializationObject.fogDensity = scene.fogDensity;
  97334. }
  97335. //Physics
  97336. if (scene.isPhysicsEnabled()) {
  97337. var physicEngine = scene.getPhysicsEngine();
  97338. if (physicEngine) {
  97339. serializationObject.physicsEnabled = true;
  97340. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  97341. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  97342. }
  97343. }
  97344. // Metadata
  97345. if (scene.metadata) {
  97346. serializationObject.metadata = scene.metadata;
  97347. }
  97348. // Morph targets
  97349. serializationObject.morphTargetManagers = [];
  97350. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  97351. var abstractMesh = _a[_i];
  97352. var manager = abstractMesh.morphTargetManager;
  97353. if (manager) {
  97354. serializationObject.morphTargetManagers.push(manager.serialize());
  97355. }
  97356. }
  97357. // Lights
  97358. serializationObject.lights = [];
  97359. var index;
  97360. var light;
  97361. for (index = 0; index < scene.lights.length; index++) {
  97362. light = scene.lights[index];
  97363. if (!light.doNotSerialize) {
  97364. serializationObject.lights.push(light.serialize());
  97365. }
  97366. }
  97367. // Cameras
  97368. serializationObject.cameras = [];
  97369. for (index = 0; index < scene.cameras.length; index++) {
  97370. var camera = scene.cameras[index];
  97371. if (!camera.doNotSerialize) {
  97372. serializationObject.cameras.push(camera.serialize());
  97373. }
  97374. }
  97375. if (scene.activeCamera) {
  97376. serializationObject.activeCameraID = scene.activeCamera.id;
  97377. }
  97378. // Animations
  97379. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  97380. // Materials
  97381. serializationObject.materials = [];
  97382. serializationObject.multiMaterials = [];
  97383. var material;
  97384. for (index = 0; index < scene.materials.length; index++) {
  97385. material = scene.materials[index];
  97386. if (!material.doNotSerialize) {
  97387. serializationObject.materials.push(material.serialize());
  97388. }
  97389. }
  97390. // MultiMaterials
  97391. serializationObject.multiMaterials = [];
  97392. for (index = 0; index < scene.multiMaterials.length; index++) {
  97393. var multiMaterial = scene.multiMaterials[index];
  97394. serializationObject.multiMaterials.push(multiMaterial.serialize());
  97395. }
  97396. // Environment texture
  97397. if (scene.environmentTexture) {
  97398. serializationObject.environmentTexture = scene.environmentTexture.name;
  97399. }
  97400. // Skeletons
  97401. serializationObject.skeletons = [];
  97402. for (index = 0; index < scene.skeletons.length; index++) {
  97403. var skeleton = scene.skeletons[index];
  97404. if (!skeleton.doNotSerialize) {
  97405. serializationObject.skeletons.push(skeleton.serialize());
  97406. }
  97407. }
  97408. // Transform nodes
  97409. serializationObject.transformNodes = [];
  97410. for (index = 0; index < scene.transformNodes.length; index++) {
  97411. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  97412. }
  97413. // Geometries
  97414. serializationObject.geometries = {};
  97415. serializationObject.geometries.boxes = [];
  97416. serializationObject.geometries.spheres = [];
  97417. serializationObject.geometries.cylinders = [];
  97418. serializationObject.geometries.toruses = [];
  97419. serializationObject.geometries.grounds = [];
  97420. serializationObject.geometries.planes = [];
  97421. serializationObject.geometries.torusKnots = [];
  97422. serializationObject.geometries.vertexData = [];
  97423. serializedGeometries = [];
  97424. var geometries = scene.getGeometries();
  97425. for (index = 0; index < geometries.length; index++) {
  97426. var geometry = geometries[index];
  97427. if (geometry.isReady()) {
  97428. serializeGeometry(geometry, serializationObject.geometries);
  97429. }
  97430. }
  97431. // Meshes
  97432. serializationObject.meshes = [];
  97433. for (index = 0; index < scene.meshes.length; index++) {
  97434. var abstractMesh = scene.meshes[index];
  97435. if (abstractMesh instanceof BABYLON.Mesh) {
  97436. var mesh = abstractMesh;
  97437. if (!mesh.doNotSerialize) {
  97438. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  97439. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  97440. }
  97441. }
  97442. }
  97443. }
  97444. // Particles Systems
  97445. serializationObject.particleSystems = [];
  97446. for (index = 0; index < scene.particleSystems.length; index++) {
  97447. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  97448. }
  97449. // Lens flares
  97450. serializationObject.lensFlareSystems = [];
  97451. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  97452. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  97453. }
  97454. // Shadows
  97455. serializationObject.shadowGenerators = [];
  97456. for (index = 0; index < scene.lights.length; index++) {
  97457. light = scene.lights[index];
  97458. var shadowGenerator = light.getShadowGenerator();
  97459. if (shadowGenerator) {
  97460. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  97461. }
  97462. }
  97463. // Action Manager
  97464. if (scene.actionManager) {
  97465. serializationObject.actions = scene.actionManager.serialize("scene");
  97466. }
  97467. // Audio
  97468. serializationObject.sounds = [];
  97469. for (index = 0; index < scene.soundTracks.length; index++) {
  97470. var soundtrack = scene.soundTracks[index];
  97471. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  97472. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  97473. }
  97474. }
  97475. // Effect layers
  97476. serializationObject.effectLayers = [];
  97477. for (index = 0; index < scene.effectLayers.length; index++) {
  97478. var layer = scene.effectLayers[index];
  97479. if (layer.serialize) {
  97480. serializationObject.effectLayers.push(layer.serialize());
  97481. }
  97482. }
  97483. return serializationObject;
  97484. };
  97485. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  97486. if (withParents === void 0) { withParents = false; }
  97487. if (withChildren === void 0) { withChildren = false; }
  97488. var serializationObject = {};
  97489. SceneSerializer.ClearCache();
  97490. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  97491. if (withParents || withChildren) {
  97492. //deliberate for loop! not for each, appended should be processed as well.
  97493. for (var i = 0; i < toSerialize.length; ++i) {
  97494. if (withChildren) {
  97495. toSerialize[i].getDescendants().forEach(function (node) {
  97496. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  97497. toSerialize.push(node);
  97498. }
  97499. });
  97500. }
  97501. //make sure the array doesn't contain the object already
  97502. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  97503. toSerialize.push(toSerialize[i].parent);
  97504. }
  97505. }
  97506. }
  97507. toSerialize.forEach(function (mesh) {
  97508. finalizeSingleMesh(mesh, serializationObject);
  97509. });
  97510. return serializationObject;
  97511. };
  97512. return SceneSerializer;
  97513. }());
  97514. BABYLON.SceneSerializer = SceneSerializer;
  97515. })(BABYLON || (BABYLON = {}));
  97516. //# sourceMappingURL=babylon.sceneSerializer.js.map
  97517. var BABYLON;
  97518. (function (BABYLON) {
  97519. var ReflectionProbe = /** @class */ (function () {
  97520. function ReflectionProbe(name, size, scene, generateMipMaps) {
  97521. if (generateMipMaps === void 0) { generateMipMaps = true; }
  97522. var _this = this;
  97523. this.name = name;
  97524. this._viewMatrix = BABYLON.Matrix.Identity();
  97525. this._target = BABYLON.Vector3.Zero();
  97526. this._add = BABYLON.Vector3.Zero();
  97527. this._invertYAxis = false;
  97528. this.position = BABYLON.Vector3.Zero();
  97529. this._scene = scene;
  97530. this._scene.reflectionProbes.push(this);
  97531. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  97532. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  97533. switch (faceIndex) {
  97534. case 0:
  97535. _this._add.copyFromFloats(1, 0, 0);
  97536. break;
  97537. case 1:
  97538. _this._add.copyFromFloats(-1, 0, 0);
  97539. break;
  97540. case 2:
  97541. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  97542. break;
  97543. case 3:
  97544. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  97545. break;
  97546. case 4:
  97547. _this._add.copyFromFloats(0, 0, 1);
  97548. break;
  97549. case 5:
  97550. _this._add.copyFromFloats(0, 0, -1);
  97551. break;
  97552. }
  97553. if (_this._attachedMesh) {
  97554. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  97555. }
  97556. _this.position.addToRef(_this._add, _this._target);
  97557. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  97558. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  97559. scene._forcedViewPosition = _this.position;
  97560. });
  97561. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  97562. scene._forcedViewPosition = null;
  97563. scene.updateTransformMatrix(true);
  97564. });
  97565. if (scene.activeCamera) {
  97566. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  97567. }
  97568. }
  97569. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  97570. get: function () {
  97571. return this._renderTargetTexture.samples;
  97572. },
  97573. set: function (value) {
  97574. this._renderTargetTexture.samples = value;
  97575. },
  97576. enumerable: true,
  97577. configurable: true
  97578. });
  97579. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  97580. get: function () {
  97581. return this._renderTargetTexture.refreshRate;
  97582. },
  97583. set: function (value) {
  97584. this._renderTargetTexture.refreshRate = value;
  97585. },
  97586. enumerable: true,
  97587. configurable: true
  97588. });
  97589. ReflectionProbe.prototype.getScene = function () {
  97590. return this._scene;
  97591. };
  97592. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  97593. get: function () {
  97594. return this._renderTargetTexture;
  97595. },
  97596. enumerable: true,
  97597. configurable: true
  97598. });
  97599. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  97600. get: function () {
  97601. return this._renderTargetTexture.renderList;
  97602. },
  97603. enumerable: true,
  97604. configurable: true
  97605. });
  97606. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  97607. this._attachedMesh = mesh;
  97608. };
  97609. /**
  97610. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  97611. *
  97612. * @param renderingGroupId The rendering group id corresponding to its index
  97613. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  97614. */
  97615. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  97616. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  97617. };
  97618. ReflectionProbe.prototype.dispose = function () {
  97619. var index = this._scene.reflectionProbes.indexOf(this);
  97620. if (index !== -1) {
  97621. // Remove from the scene if found
  97622. this._scene.reflectionProbes.splice(index, 1);
  97623. }
  97624. if (this._renderTargetTexture) {
  97625. this._renderTargetTexture.dispose();
  97626. this._renderTargetTexture = null;
  97627. }
  97628. };
  97629. return ReflectionProbe;
  97630. }());
  97631. BABYLON.ReflectionProbe = ReflectionProbe;
  97632. })(BABYLON || (BABYLON = {}));
  97633. //# sourceMappingURL=babylon.reflectionProbe.js.map
  97634. var BABYLON;
  97635. (function (BABYLON) {
  97636. var Layer = /** @class */ (function () {
  97637. function Layer(name, imgUrl, scene, isBackground, color) {
  97638. this.name = name;
  97639. this.scale = new BABYLON.Vector2(1, 1);
  97640. this.offset = new BABYLON.Vector2(0, 0);
  97641. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  97642. this.layerMask = 0x0FFFFFFF;
  97643. this._vertexBuffers = {};
  97644. // Events
  97645. /**
  97646. * An event triggered when the layer is disposed.
  97647. */
  97648. this.onDisposeObservable = new BABYLON.Observable();
  97649. /**
  97650. * An event triggered before rendering the scene
  97651. */
  97652. this.onBeforeRenderObservable = new BABYLON.Observable();
  97653. /**
  97654. * An event triggered after rendering the scene
  97655. */
  97656. this.onAfterRenderObservable = new BABYLON.Observable();
  97657. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  97658. this.isBackground = isBackground === undefined ? true : isBackground;
  97659. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  97660. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  97661. this._scene.layers.push(this);
  97662. var engine = this._scene.getEngine();
  97663. // VBO
  97664. var vertices = [];
  97665. vertices.push(1, 1);
  97666. vertices.push(-1, 1);
  97667. vertices.push(-1, -1);
  97668. vertices.push(1, -1);
  97669. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  97670. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  97671. this._createIndexBuffer();
  97672. // Effects
  97673. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  97674. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  97675. }
  97676. Object.defineProperty(Layer.prototype, "onDispose", {
  97677. set: function (callback) {
  97678. if (this._onDisposeObserver) {
  97679. this.onDisposeObservable.remove(this._onDisposeObserver);
  97680. }
  97681. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  97682. },
  97683. enumerable: true,
  97684. configurable: true
  97685. });
  97686. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  97687. set: function (callback) {
  97688. if (this._onBeforeRenderObserver) {
  97689. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  97690. }
  97691. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  97692. },
  97693. enumerable: true,
  97694. configurable: true
  97695. });
  97696. Object.defineProperty(Layer.prototype, "onAfterRender", {
  97697. set: function (callback) {
  97698. if (this._onAfterRenderObserver) {
  97699. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  97700. }
  97701. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  97702. },
  97703. enumerable: true,
  97704. configurable: true
  97705. });
  97706. Layer.prototype._createIndexBuffer = function () {
  97707. var engine = this._scene.getEngine();
  97708. // Indices
  97709. var indices = [];
  97710. indices.push(0);
  97711. indices.push(1);
  97712. indices.push(2);
  97713. indices.push(0);
  97714. indices.push(2);
  97715. indices.push(3);
  97716. this._indexBuffer = engine.createIndexBuffer(indices);
  97717. };
  97718. Layer.prototype._rebuild = function () {
  97719. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97720. if (vb) {
  97721. vb._rebuild();
  97722. }
  97723. this._createIndexBuffer();
  97724. };
  97725. Layer.prototype.render = function () {
  97726. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  97727. // Check
  97728. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  97729. return;
  97730. var engine = this._scene.getEngine();
  97731. this.onBeforeRenderObservable.notifyObservers(this);
  97732. // Render
  97733. engine.enableEffect(currentEffect);
  97734. engine.setState(false);
  97735. // Texture
  97736. currentEffect.setTexture("textureSampler", this.texture);
  97737. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  97738. // Color
  97739. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  97740. // Scale / offset
  97741. currentEffect.setVector2("offset", this.offset);
  97742. currentEffect.setVector2("scale", this.scale);
  97743. // VBOs
  97744. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  97745. // Draw order
  97746. if (!this.alphaTest) {
  97747. engine.setAlphaMode(this.alphaBlendingMode);
  97748. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97749. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  97750. }
  97751. else {
  97752. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97753. }
  97754. this.onAfterRenderObservable.notifyObservers(this);
  97755. };
  97756. Layer.prototype.dispose = function () {
  97757. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97758. if (vertexBuffer) {
  97759. vertexBuffer.dispose();
  97760. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  97761. }
  97762. if (this._indexBuffer) {
  97763. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  97764. this._indexBuffer = null;
  97765. }
  97766. if (this.texture) {
  97767. this.texture.dispose();
  97768. this.texture = null;
  97769. }
  97770. // Remove from scene
  97771. var index = this._scene.layers.indexOf(this);
  97772. this._scene.layers.splice(index, 1);
  97773. // Callback
  97774. this.onDisposeObservable.notifyObservers(this);
  97775. this.onDisposeObservable.clear();
  97776. this.onAfterRenderObservable.clear();
  97777. this.onBeforeRenderObservable.clear();
  97778. };
  97779. return Layer;
  97780. }());
  97781. BABYLON.Layer = Layer;
  97782. })(BABYLON || (BABYLON = {}));
  97783. //# sourceMappingURL=babylon.layer.js.map
  97784. var BABYLON;
  97785. (function (BABYLON) {
  97786. var TextureTools = /** @class */ (function () {
  97787. function TextureTools() {
  97788. }
  97789. /**
  97790. * Uses the GPU to create a copy texture rescaled at a given size
  97791. * @param texture Texture to copy from
  97792. * @param width Desired width
  97793. * @param height Desired height
  97794. * @return Generated texture
  97795. */
  97796. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  97797. if (useBilinearMode === void 0) { useBilinearMode = true; }
  97798. var scene = texture.getScene();
  97799. var engine = scene.getEngine();
  97800. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  97801. rtt.wrapU = texture.wrapU;
  97802. rtt.wrapV = texture.wrapV;
  97803. rtt.uOffset = texture.uOffset;
  97804. rtt.vOffset = texture.vOffset;
  97805. rtt.uScale = texture.uScale;
  97806. rtt.vScale = texture.vScale;
  97807. rtt.uAng = texture.uAng;
  97808. rtt.vAng = texture.vAng;
  97809. rtt.wAng = texture.wAng;
  97810. rtt.coordinatesIndex = texture.coordinatesIndex;
  97811. rtt.level = texture.level;
  97812. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  97813. rtt._texture.isReady = false;
  97814. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97815. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97816. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  97817. passPostProcess.getEffect().executeWhenCompiled(function () {
  97818. passPostProcess.onApply = function (effect) {
  97819. effect.setTexture("textureSampler", texture);
  97820. };
  97821. var internalTexture = rtt.getInternalTexture();
  97822. if (internalTexture) {
  97823. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  97824. engine.unBindFramebuffer(internalTexture);
  97825. rtt.disposeFramebufferObjects();
  97826. passPostProcess.dispose();
  97827. internalTexture.isReady = true;
  97828. }
  97829. });
  97830. return rtt;
  97831. };
  97832. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  97833. if (!scene._environmentBRDFTexture) {
  97834. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97835. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97836. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97837. scene._environmentBRDFTexture = texture;
  97838. }
  97839. return scene._environmentBRDFTexture;
  97840. };
  97841. 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=";
  97842. return TextureTools;
  97843. }());
  97844. BABYLON.TextureTools = TextureTools;
  97845. })(BABYLON || (BABYLON = {}));
  97846. //# sourceMappingURL=babylon.textureTools.js.map
  97847. var BABYLON;
  97848. (function (BABYLON) {
  97849. var FramingBehavior = /** @class */ (function () {
  97850. function FramingBehavior() {
  97851. this._mode = FramingBehavior.FitFrustumSidesMode;
  97852. this._radiusScale = 1.0;
  97853. this._positionScale = 0.5;
  97854. this._defaultElevation = 0.3;
  97855. this._elevationReturnTime = 1500;
  97856. this._elevationReturnWaitTime = 1000;
  97857. this._zoomStopsAnimation = false;
  97858. this._framingTime = 1500;
  97859. this._isPointerDown = false;
  97860. this._lastInteractionTime = -Infinity;
  97861. // Framing control
  97862. this._animatables = new Array();
  97863. this._betaIsAnimating = false;
  97864. }
  97865. Object.defineProperty(FramingBehavior.prototype, "name", {
  97866. get: function () {
  97867. return "Framing";
  97868. },
  97869. enumerable: true,
  97870. configurable: true
  97871. });
  97872. Object.defineProperty(FramingBehavior.prototype, "mode", {
  97873. /**
  97874. * Gets current mode used by the behavior.
  97875. */
  97876. get: function () {
  97877. return this._mode;
  97878. },
  97879. /**
  97880. * Sets the current mode used by the behavior
  97881. */
  97882. set: function (mode) {
  97883. this._mode = mode;
  97884. },
  97885. enumerable: true,
  97886. configurable: true
  97887. });
  97888. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  97889. /**
  97890. * Gets the scale applied to the radius
  97891. */
  97892. get: function () {
  97893. return this._radiusScale;
  97894. },
  97895. /**
  97896. * Sets the scale applied to the radius (1 by default)
  97897. */
  97898. set: function (radius) {
  97899. this._radiusScale = radius;
  97900. },
  97901. enumerable: true,
  97902. configurable: true
  97903. });
  97904. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  97905. /**
  97906. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  97907. */
  97908. get: function () {
  97909. return this._positionScale;
  97910. },
  97911. /**
  97912. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  97913. */
  97914. set: function (scale) {
  97915. this._positionScale = scale;
  97916. },
  97917. enumerable: true,
  97918. configurable: true
  97919. });
  97920. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  97921. /**
  97922. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  97923. * behaviour is triggered, in radians.
  97924. */
  97925. get: function () {
  97926. return this._defaultElevation;
  97927. },
  97928. /**
  97929. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  97930. * behaviour is triggered, in radians.
  97931. */
  97932. set: function (elevation) {
  97933. this._defaultElevation = elevation;
  97934. },
  97935. enumerable: true,
  97936. configurable: true
  97937. });
  97938. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  97939. /**
  97940. * Gets the time (in milliseconds) taken to return to the default beta position.
  97941. * Negative value indicates camera should not return to default.
  97942. */
  97943. get: function () {
  97944. return this._elevationReturnTime;
  97945. },
  97946. /**
  97947. * Sets the time (in milliseconds) taken to return to the default beta position.
  97948. * Negative value indicates camera should not return to default.
  97949. */
  97950. set: function (speed) {
  97951. this._elevationReturnTime = speed;
  97952. },
  97953. enumerable: true,
  97954. configurable: true
  97955. });
  97956. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  97957. /**
  97958. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  97959. */
  97960. get: function () {
  97961. return this._elevationReturnWaitTime;
  97962. },
  97963. /**
  97964. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  97965. */
  97966. set: function (time) {
  97967. this._elevationReturnWaitTime = time;
  97968. },
  97969. enumerable: true,
  97970. configurable: true
  97971. });
  97972. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  97973. /**
  97974. * Gets the flag that indicates if user zooming should stop animation.
  97975. */
  97976. get: function () {
  97977. return this._zoomStopsAnimation;
  97978. },
  97979. /**
  97980. * Sets the flag that indicates if user zooming should stop animation.
  97981. */
  97982. set: function (flag) {
  97983. this._zoomStopsAnimation = flag;
  97984. },
  97985. enumerable: true,
  97986. configurable: true
  97987. });
  97988. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  97989. /**
  97990. * Gets the transition time when framing the mesh, in milliseconds
  97991. */
  97992. get: function () {
  97993. return this._framingTime;
  97994. },
  97995. /**
  97996. * Sets the transition time when framing the mesh, in milliseconds
  97997. */
  97998. set: function (time) {
  97999. this._framingTime = time;
  98000. },
  98001. enumerable: true,
  98002. configurable: true
  98003. });
  98004. FramingBehavior.prototype.init = function () {
  98005. // Do notihng
  98006. };
  98007. FramingBehavior.prototype.attach = function (camera) {
  98008. var _this = this;
  98009. this._attachedCamera = camera;
  98010. var scene = this._attachedCamera.getScene();
  98011. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  98012. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  98013. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  98014. _this._isPointerDown = true;
  98015. return;
  98016. }
  98017. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  98018. _this._isPointerDown = false;
  98019. }
  98020. });
  98021. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  98022. if (mesh) {
  98023. _this.zoomOnMesh(mesh);
  98024. }
  98025. });
  98026. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  98027. // Stop the animation if there is user interaction and the animation should stop for this interaction
  98028. _this._applyUserInteraction();
  98029. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  98030. // back to the default position after a given timeout
  98031. _this._maintainCameraAboveGround();
  98032. });
  98033. };
  98034. FramingBehavior.prototype.detach = function () {
  98035. if (!this._attachedCamera) {
  98036. return;
  98037. }
  98038. var scene = this._attachedCamera.getScene();
  98039. if (this._onPrePointerObservableObserver) {
  98040. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  98041. }
  98042. if (this._onAfterCheckInputsObserver) {
  98043. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  98044. }
  98045. if (this._onMeshTargetChangedObserver) {
  98046. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  98047. }
  98048. this._attachedCamera = null;
  98049. };
  98050. /**
  98051. * Targets the given mesh and updates zoom level accordingly.
  98052. * @param mesh The mesh to target.
  98053. * @param radius Optional. If a cached radius position already exists, overrides default.
  98054. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98055. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98056. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98057. */
  98058. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  98059. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98060. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98061. mesh.computeWorldMatrix(true);
  98062. var boundingBox = mesh.getBoundingInfo().boundingBox;
  98063. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  98064. };
  98065. /**
  98066. * Targets the given mesh with its children and updates zoom level accordingly.
  98067. * @param mesh The mesh to target.
  98068. * @param radius Optional. If a cached radius position already exists, overrides default.
  98069. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98070. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98071. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98072. */
  98073. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  98074. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98075. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98076. mesh.computeWorldMatrix(true);
  98077. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  98078. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  98079. };
  98080. /**
  98081. * Targets the given meshes with their children and updates zoom level accordingly.
  98082. * @param meshes The mesh to target.
  98083. * @param radius Optional. If a cached radius position already exists, overrides default.
  98084. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98085. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98086. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98087. */
  98088. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  98089. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98090. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98091. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  98092. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  98093. for (var i = 0; i < meshes.length; i++) {
  98094. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  98095. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  98096. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  98097. }
  98098. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  98099. };
  98100. /**
  98101. * Targets the given mesh and updates zoom level accordingly.
  98102. * @param mesh The mesh to target.
  98103. * @param radius Optional. If a cached radius position already exists, overrides default.
  98104. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98105. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98106. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98107. */
  98108. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  98109. var _this = this;
  98110. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98111. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98112. var zoomTarget;
  98113. if (!this._attachedCamera) {
  98114. return;
  98115. }
  98116. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  98117. var bottom = minimumWorld.y;
  98118. var top = maximumWorld.y;
  98119. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  98120. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  98121. if (focusOnOriginXZ) {
  98122. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  98123. }
  98124. else {
  98125. var centerWorld = minimumWorld.add(radiusWorld);
  98126. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  98127. }
  98128. if (!this._vectorTransition) {
  98129. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  98130. }
  98131. this._betaIsAnimating = true;
  98132. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  98133. if (animatable) {
  98134. this._animatables.push(animatable);
  98135. }
  98136. // sets the radius and lower radius bounds
  98137. // Small delta ensures camera is not always at lower zoom limit.
  98138. var radius = 0;
  98139. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  98140. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  98141. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  98142. radius = position;
  98143. }
  98144. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  98145. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  98146. if (this._attachedCamera.lowerRadiusLimit === null) {
  98147. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  98148. }
  98149. }
  98150. // Set sensibilities
  98151. var extend = maximumWorld.subtract(minimumWorld).length();
  98152. this._attachedCamera.panningSensibility = 5000 / extend;
  98153. this._attachedCamera.wheelPrecision = 100 / radius;
  98154. // transition to new radius
  98155. if (!this._radiusTransition) {
  98156. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  98157. }
  98158. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  98159. _this.stopAllAnimations();
  98160. if (onAnimationEnd) {
  98161. onAnimationEnd();
  98162. }
  98163. if (_this._attachedCamera) {
  98164. _this._attachedCamera.storeState();
  98165. }
  98166. });
  98167. if (animatable) {
  98168. this._animatables.push(animatable);
  98169. }
  98170. };
  98171. /**
  98172. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  98173. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  98174. * frustum width.
  98175. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  98176. * to fully enclose the mesh in the viewing frustum.
  98177. */
  98178. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  98179. var size = maximumWorld.subtract(minimumWorld);
  98180. var boxVectorGlobalDiagonal = size.length();
  98181. var frustumSlope = this._getFrustumSlope();
  98182. // Formula for setting distance
  98183. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  98184. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  98185. // Horizon distance
  98186. var radius = radiusWithoutFraming * this._radiusScale;
  98187. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  98188. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  98189. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  98190. var camera = this._attachedCamera;
  98191. if (!camera) {
  98192. return 0;
  98193. }
  98194. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  98195. // Don't exceed the requested limit
  98196. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  98197. }
  98198. // Don't exceed the upper radius limit
  98199. if (camera.upperRadiusLimit) {
  98200. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  98201. }
  98202. return distance;
  98203. };
  98204. /**
  98205. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  98206. * is automatically returned to its default position (expected to be above ground plane).
  98207. */
  98208. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  98209. var _this = this;
  98210. if (this._elevationReturnTime < 0) {
  98211. return;
  98212. }
  98213. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  98214. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  98215. var limitBeta = Math.PI * 0.5;
  98216. // Bring the camera back up if below the ground plane
  98217. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  98218. this._betaIsAnimating = true;
  98219. //Transition to new position
  98220. this.stopAllAnimations();
  98221. if (!this._betaTransition) {
  98222. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  98223. }
  98224. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  98225. _this._clearAnimationLocks();
  98226. _this.stopAllAnimations();
  98227. });
  98228. if (animatabe) {
  98229. this._animatables.push(animatabe);
  98230. }
  98231. }
  98232. };
  98233. /**
  98234. * Returns the frustum slope based on the canvas ratio and camera FOV
  98235. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  98236. */
  98237. FramingBehavior.prototype._getFrustumSlope = function () {
  98238. // Calculate the viewport ratio
  98239. // Aspect Ratio is Height/Width.
  98240. var camera = this._attachedCamera;
  98241. if (!camera) {
  98242. return BABYLON.Vector2.Zero();
  98243. }
  98244. var engine = camera.getScene().getEngine();
  98245. var aspectRatio = engine.getAspectRatio(camera);
  98246. // Camera FOV is the vertical field of view (top-bottom) in radians.
  98247. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  98248. var frustumSlopeY = Math.tan(camera.fov / 2);
  98249. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  98250. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  98251. // along the forward vector.
  98252. var frustumSlopeX = frustumSlopeY * aspectRatio;
  98253. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  98254. };
  98255. /**
  98256. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  98257. */
  98258. FramingBehavior.prototype._clearAnimationLocks = function () {
  98259. this._betaIsAnimating = false;
  98260. };
  98261. /**
  98262. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  98263. */
  98264. FramingBehavior.prototype._applyUserInteraction = function () {
  98265. if (this.isUserIsMoving) {
  98266. this._lastInteractionTime = BABYLON.Tools.Now;
  98267. this.stopAllAnimations();
  98268. this._clearAnimationLocks();
  98269. }
  98270. };
  98271. /**
  98272. * Stops and removes all animations that have been applied to the camera
  98273. */
  98274. FramingBehavior.prototype.stopAllAnimations = function () {
  98275. if (this._attachedCamera) {
  98276. this._attachedCamera.animations = [];
  98277. }
  98278. while (this._animatables.length) {
  98279. if (this._animatables[0]) {
  98280. this._animatables[0].onAnimationEnd = null;
  98281. this._animatables[0].stop();
  98282. }
  98283. this._animatables.shift();
  98284. }
  98285. };
  98286. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  98287. /**
  98288. * Gets a value indicating if the user is moving the camera
  98289. */
  98290. get: function () {
  98291. if (!this._attachedCamera) {
  98292. return false;
  98293. }
  98294. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  98295. this._attachedCamera.inertialBetaOffset !== 0 ||
  98296. this._attachedCamera.inertialRadiusOffset !== 0 ||
  98297. this._attachedCamera.inertialPanningX !== 0 ||
  98298. this._attachedCamera.inertialPanningY !== 0 ||
  98299. this._isPointerDown;
  98300. },
  98301. enumerable: true,
  98302. configurable: true
  98303. });
  98304. /**
  98305. * The easing function used by animations
  98306. */
  98307. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  98308. /**
  98309. * The easing mode used by animations
  98310. */
  98311. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  98312. // Statics
  98313. /**
  98314. * The camera can move all the way towards the mesh.
  98315. */
  98316. FramingBehavior.IgnoreBoundsSizeMode = 0;
  98317. /**
  98318. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  98319. */
  98320. FramingBehavior.FitFrustumSidesMode = 1;
  98321. return FramingBehavior;
  98322. }());
  98323. BABYLON.FramingBehavior = FramingBehavior;
  98324. })(BABYLON || (BABYLON = {}));
  98325. //# sourceMappingURL=babylon.framingBehavior.js.map
  98326. var BABYLON;
  98327. (function (BABYLON) {
  98328. /**
  98329. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  98330. */
  98331. var BouncingBehavior = /** @class */ (function () {
  98332. function BouncingBehavior() {
  98333. /**
  98334. * The duration of the animation, in milliseconds
  98335. */
  98336. this.transitionDuration = 450;
  98337. /**
  98338. * Length of the distance animated by the transition when lower radius is reached
  98339. */
  98340. this.lowerRadiusTransitionRange = 2;
  98341. /**
  98342. * Length of the distance animated by the transition when upper radius is reached
  98343. */
  98344. this.upperRadiusTransitionRange = -2;
  98345. this._autoTransitionRange = false;
  98346. // Animations
  98347. this._radiusIsAnimating = false;
  98348. this._radiusBounceTransition = null;
  98349. this._animatables = new Array();
  98350. }
  98351. Object.defineProperty(BouncingBehavior.prototype, "name", {
  98352. get: function () {
  98353. return "Bouncing";
  98354. },
  98355. enumerable: true,
  98356. configurable: true
  98357. });
  98358. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  98359. /**
  98360. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  98361. */
  98362. get: function () {
  98363. return this._autoTransitionRange;
  98364. },
  98365. /**
  98366. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  98367. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  98368. */
  98369. set: function (value) {
  98370. var _this = this;
  98371. if (this._autoTransitionRange === value) {
  98372. return;
  98373. }
  98374. this._autoTransitionRange = value;
  98375. var camera = this._attachedCamera;
  98376. if (!camera) {
  98377. return;
  98378. }
  98379. if (value) {
  98380. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  98381. if (!mesh) {
  98382. return;
  98383. }
  98384. mesh.computeWorldMatrix(true);
  98385. var diagonal = mesh.getBoundingInfo().diagonalLength;
  98386. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  98387. _this.upperRadiusTransitionRange = diagonal * 0.05;
  98388. });
  98389. }
  98390. else if (this._onMeshTargetChangedObserver) {
  98391. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  98392. }
  98393. },
  98394. enumerable: true,
  98395. configurable: true
  98396. });
  98397. BouncingBehavior.prototype.init = function () {
  98398. // Do notihng
  98399. };
  98400. BouncingBehavior.prototype.attach = function (camera) {
  98401. var _this = this;
  98402. this._attachedCamera = camera;
  98403. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  98404. if (!_this._attachedCamera) {
  98405. return;
  98406. }
  98407. // Add the bounce animation to the lower radius limit
  98408. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  98409. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  98410. }
  98411. // Add the bounce animation to the upper radius limit
  98412. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  98413. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  98414. }
  98415. });
  98416. };
  98417. BouncingBehavior.prototype.detach = function () {
  98418. if (!this._attachedCamera) {
  98419. return;
  98420. }
  98421. if (this._onAfterCheckInputsObserver) {
  98422. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  98423. }
  98424. if (this._onMeshTargetChangedObserver) {
  98425. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  98426. }
  98427. this._attachedCamera = null;
  98428. };
  98429. /**
  98430. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  98431. * @param radiusLimit The limit to check against.
  98432. * @return Bool to indicate if at limit.
  98433. */
  98434. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  98435. if (!this._attachedCamera) {
  98436. return false;
  98437. }
  98438. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  98439. return true;
  98440. }
  98441. return false;
  98442. };
  98443. /**
  98444. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  98445. * @param radiusDelta The delta by which to animate to. Can be negative.
  98446. */
  98447. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  98448. var _this = this;
  98449. if (!this._attachedCamera) {
  98450. return;
  98451. }
  98452. if (!this._radiusBounceTransition) {
  98453. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  98454. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  98455. }
  98456. // Prevent zoom until bounce has completed
  98457. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  98458. this._attachedCamera.wheelPrecision = Infinity;
  98459. this._attachedCamera.inertialRadiusOffset = 0;
  98460. // Animate to the radius limit
  98461. this.stopAllAnimations();
  98462. this._radiusIsAnimating = true;
  98463. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  98464. if (animatable) {
  98465. this._animatables.push(animatable);
  98466. }
  98467. };
  98468. /**
  98469. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  98470. */
  98471. BouncingBehavior.prototype._clearAnimationLocks = function () {
  98472. this._radiusIsAnimating = false;
  98473. if (this._attachedCamera) {
  98474. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  98475. }
  98476. };
  98477. /**
  98478. * Stops and removes all animations that have been applied to the camera
  98479. */
  98480. BouncingBehavior.prototype.stopAllAnimations = function () {
  98481. if (this._attachedCamera) {
  98482. this._attachedCamera.animations = [];
  98483. }
  98484. while (this._animatables.length) {
  98485. this._animatables[0].onAnimationEnd = null;
  98486. this._animatables[0].stop();
  98487. this._animatables.shift();
  98488. }
  98489. };
  98490. /**
  98491. * The easing function used by animations
  98492. */
  98493. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  98494. /**
  98495. * The easing mode used by animations
  98496. */
  98497. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  98498. return BouncingBehavior;
  98499. }());
  98500. BABYLON.BouncingBehavior = BouncingBehavior;
  98501. })(BABYLON || (BABYLON = {}));
  98502. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  98503. var BABYLON;
  98504. (function (BABYLON) {
  98505. var AutoRotationBehavior = /** @class */ (function () {
  98506. function AutoRotationBehavior() {
  98507. this._zoomStopsAnimation = false;
  98508. this._idleRotationSpeed = 0.05;
  98509. this._idleRotationWaitTime = 2000;
  98510. this._idleRotationSpinupTime = 2000;
  98511. this._isPointerDown = false;
  98512. this._lastFrameTime = null;
  98513. this._lastInteractionTime = -Infinity;
  98514. this._cameraRotationSpeed = 0;
  98515. this._lastFrameRadius = 0;
  98516. }
  98517. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  98518. get: function () {
  98519. return "AutoRotation";
  98520. },
  98521. enumerable: true,
  98522. configurable: true
  98523. });
  98524. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  98525. /**
  98526. * Gets the flag that indicates if user zooming should stop animation.
  98527. */
  98528. get: function () {
  98529. return this._zoomStopsAnimation;
  98530. },
  98531. /**
  98532. * Sets the flag that indicates if user zooming should stop animation.
  98533. */
  98534. set: function (flag) {
  98535. this._zoomStopsAnimation = flag;
  98536. },
  98537. enumerable: true,
  98538. configurable: true
  98539. });
  98540. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  98541. /**
  98542. * Gets the default speed at which the camera rotates around the model.
  98543. */
  98544. get: function () {
  98545. return this._idleRotationSpeed;
  98546. },
  98547. /**
  98548. * Sets the default speed at which the camera rotates around the model.
  98549. */
  98550. set: function (speed) {
  98551. this._idleRotationSpeed = speed;
  98552. },
  98553. enumerable: true,
  98554. configurable: true
  98555. });
  98556. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  98557. /**
  98558. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  98559. */
  98560. get: function () {
  98561. return this._idleRotationWaitTime;
  98562. },
  98563. /**
  98564. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  98565. */
  98566. set: function (time) {
  98567. this._idleRotationWaitTime = time;
  98568. },
  98569. enumerable: true,
  98570. configurable: true
  98571. });
  98572. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  98573. /**
  98574. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  98575. */
  98576. get: function () {
  98577. return this._idleRotationSpinupTime;
  98578. },
  98579. /**
  98580. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  98581. */
  98582. set: function (time) {
  98583. this._idleRotationSpinupTime = time;
  98584. },
  98585. enumerable: true,
  98586. configurable: true
  98587. });
  98588. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  98589. /**
  98590. * Gets a value indicating if the camera is currently rotating because of this behavior
  98591. */
  98592. get: function () {
  98593. return Math.abs(this._cameraRotationSpeed) > 0;
  98594. },
  98595. enumerable: true,
  98596. configurable: true
  98597. });
  98598. AutoRotationBehavior.prototype.init = function () {
  98599. // Do notihng
  98600. };
  98601. AutoRotationBehavior.prototype.attach = function (camera) {
  98602. var _this = this;
  98603. this._attachedCamera = camera;
  98604. var scene = this._attachedCamera.getScene();
  98605. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  98606. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  98607. _this._isPointerDown = true;
  98608. return;
  98609. }
  98610. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  98611. _this._isPointerDown = false;
  98612. }
  98613. });
  98614. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  98615. var now = BABYLON.Tools.Now;
  98616. var dt = 0;
  98617. if (_this._lastFrameTime != null) {
  98618. dt = now - _this._lastFrameTime;
  98619. }
  98620. _this._lastFrameTime = now;
  98621. // Stop the animation if there is user interaction and the animation should stop for this interaction
  98622. _this._applyUserInteraction();
  98623. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  98624. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  98625. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  98626. // Step camera rotation by rotation speed
  98627. if (_this._attachedCamera) {
  98628. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  98629. }
  98630. });
  98631. };
  98632. AutoRotationBehavior.prototype.detach = function () {
  98633. if (!this._attachedCamera) {
  98634. return;
  98635. }
  98636. var scene = this._attachedCamera.getScene();
  98637. if (this._onPrePointerObservableObserver) {
  98638. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  98639. }
  98640. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  98641. this._attachedCamera = null;
  98642. };
  98643. /**
  98644. * Returns true if user is scrolling.
  98645. * @return true if user is scrolling.
  98646. */
  98647. AutoRotationBehavior.prototype._userIsZooming = function () {
  98648. if (!this._attachedCamera) {
  98649. return false;
  98650. }
  98651. return this._attachedCamera.inertialRadiusOffset !== 0;
  98652. };
  98653. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  98654. if (!this._attachedCamera) {
  98655. return false;
  98656. }
  98657. var zoomHasHitLimit = false;
  98658. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  98659. zoomHasHitLimit = true;
  98660. }
  98661. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  98662. this._lastFrameRadius = this._attachedCamera.radius;
  98663. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  98664. };
  98665. /**
  98666. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  98667. */
  98668. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  98669. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  98670. this._lastInteractionTime = BABYLON.Tools.Now;
  98671. }
  98672. };
  98673. // Tools
  98674. AutoRotationBehavior.prototype._userIsMoving = function () {
  98675. if (!this._attachedCamera) {
  98676. return false;
  98677. }
  98678. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  98679. this._attachedCamera.inertialBetaOffset !== 0 ||
  98680. this._attachedCamera.inertialRadiusOffset !== 0 ||
  98681. this._attachedCamera.inertialPanningX !== 0 ||
  98682. this._attachedCamera.inertialPanningY !== 0 ||
  98683. this._isPointerDown;
  98684. };
  98685. return AutoRotationBehavior;
  98686. }());
  98687. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  98688. })(BABYLON || (BABYLON = {}));
  98689. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  98690. var BABYLON;
  98691. (function (BABYLON) {
  98692. var NullEngineOptions = /** @class */ (function () {
  98693. function NullEngineOptions() {
  98694. this.renderWidth = 512;
  98695. this.renderHeight = 256;
  98696. this.textureSize = 512;
  98697. this.deterministicLockstep = false;
  98698. this.lockstepMaxSteps = 4;
  98699. }
  98700. return NullEngineOptions;
  98701. }());
  98702. BABYLON.NullEngineOptions = NullEngineOptions;
  98703. /**
  98704. * The null engine class provides support for headless version of babylon.js.
  98705. * This can be used in server side scenario or for testing purposes
  98706. */
  98707. var NullEngine = /** @class */ (function (_super) {
  98708. __extends(NullEngine, _super);
  98709. function NullEngine(options) {
  98710. if (options === void 0) { options = new NullEngineOptions(); }
  98711. var _this = _super.call(this, null) || this;
  98712. if (options.deterministicLockstep === undefined) {
  98713. options.deterministicLockstep = false;
  98714. }
  98715. if (options.lockstepMaxSteps === undefined) {
  98716. options.lockstepMaxSteps = 4;
  98717. }
  98718. _this._options = options;
  98719. // Init caps
  98720. // We consider we are on a webgl1 capable device
  98721. _this._caps = new BABYLON.EngineCapabilities();
  98722. _this._caps.maxTexturesImageUnits = 16;
  98723. _this._caps.maxVertexTextureImageUnits = 16;
  98724. _this._caps.maxTextureSize = 512;
  98725. _this._caps.maxCubemapTextureSize = 512;
  98726. _this._caps.maxRenderTextureSize = 512;
  98727. _this._caps.maxVertexAttribs = 16;
  98728. _this._caps.maxVaryingVectors = 16;
  98729. _this._caps.maxFragmentUniformVectors = 16;
  98730. _this._caps.maxVertexUniformVectors = 16;
  98731. // Extensions
  98732. _this._caps.standardDerivatives = false;
  98733. _this._caps.astc = null;
  98734. _this._caps.s3tc = null;
  98735. _this._caps.pvrtc = null;
  98736. _this._caps.etc1 = null;
  98737. _this._caps.etc2 = null;
  98738. _this._caps.textureAnisotropicFilterExtension = null;
  98739. _this._caps.maxAnisotropy = 0;
  98740. _this._caps.uintIndices = false;
  98741. _this._caps.fragmentDepthSupported = false;
  98742. _this._caps.highPrecisionShaderSupported = true;
  98743. _this._caps.colorBufferFloat = false;
  98744. _this._caps.textureFloat = false;
  98745. _this._caps.textureFloatLinearFiltering = false;
  98746. _this._caps.textureFloatRender = false;
  98747. _this._caps.textureHalfFloat = false;
  98748. _this._caps.textureHalfFloatLinearFiltering = false;
  98749. _this._caps.textureHalfFloatRender = false;
  98750. _this._caps.textureLOD = false;
  98751. _this._caps.drawBuffersExtension = false;
  98752. _this._caps.depthTextureExtension = false;
  98753. _this._caps.vertexArrayObject = false;
  98754. _this._caps.instancedArrays = false;
  98755. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  98756. // Wrappers
  98757. if (typeof URL === "undefined") {
  98758. URL = {
  98759. createObjectURL: function () { },
  98760. revokeObjectURL: function () { }
  98761. };
  98762. }
  98763. if (typeof Blob === "undefined") {
  98764. Blob = function () { };
  98765. }
  98766. return _this;
  98767. }
  98768. NullEngine.prototype.isDeterministicLockStep = function () {
  98769. return this._options.deterministicLockstep;
  98770. };
  98771. NullEngine.prototype.getLockstepMaxSteps = function () {
  98772. return this._options.lockstepMaxSteps;
  98773. };
  98774. NullEngine.prototype.getHardwareScalingLevel = function () {
  98775. return 1.0;
  98776. };
  98777. NullEngine.prototype.createVertexBuffer = function (vertices) {
  98778. return {
  98779. capacity: 0,
  98780. references: 1,
  98781. is32Bits: false
  98782. };
  98783. };
  98784. NullEngine.prototype.createIndexBuffer = function (indices) {
  98785. return {
  98786. capacity: 0,
  98787. references: 1,
  98788. is32Bits: false
  98789. };
  98790. };
  98791. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  98792. if (stencil === void 0) { stencil = false; }
  98793. };
  98794. NullEngine.prototype.getRenderWidth = function (useScreen) {
  98795. if (useScreen === void 0) { useScreen = false; }
  98796. if (!useScreen && this._currentRenderTarget) {
  98797. return this._currentRenderTarget.width;
  98798. }
  98799. return this._options.renderWidth;
  98800. };
  98801. NullEngine.prototype.getRenderHeight = function (useScreen) {
  98802. if (useScreen === void 0) { useScreen = false; }
  98803. if (!useScreen && this._currentRenderTarget) {
  98804. return this._currentRenderTarget.height;
  98805. }
  98806. return this._options.renderHeight;
  98807. };
  98808. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  98809. this._cachedViewport = viewport;
  98810. };
  98811. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  98812. return {
  98813. transformFeedback: null,
  98814. __SPECTOR_rebuildProgram: null
  98815. };
  98816. };
  98817. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  98818. return [];
  98819. };
  98820. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  98821. return [];
  98822. };
  98823. NullEngine.prototype.bindSamplers = function (effect) {
  98824. this._currentEffect = null;
  98825. };
  98826. NullEngine.prototype.enableEffect = function (effect) {
  98827. this._currentEffect = effect;
  98828. if (effect.onBind) {
  98829. effect.onBind(effect);
  98830. }
  98831. effect.onBindObservable.notifyObservers(effect);
  98832. };
  98833. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  98834. if (zOffset === void 0) { zOffset = 0; }
  98835. if (reverseSide === void 0) { reverseSide = false; }
  98836. };
  98837. NullEngine.prototype.setIntArray = function (uniform, array) {
  98838. };
  98839. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  98840. };
  98841. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  98842. };
  98843. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  98844. };
  98845. NullEngine.prototype.setFloatArray = function (uniform, array) {
  98846. };
  98847. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  98848. };
  98849. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  98850. };
  98851. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  98852. };
  98853. NullEngine.prototype.setArray = function (uniform, array) {
  98854. };
  98855. NullEngine.prototype.setArray2 = function (uniform, array) {
  98856. };
  98857. NullEngine.prototype.setArray3 = function (uniform, array) {
  98858. };
  98859. NullEngine.prototype.setArray4 = function (uniform, array) {
  98860. };
  98861. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  98862. };
  98863. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  98864. };
  98865. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  98866. };
  98867. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  98868. };
  98869. NullEngine.prototype.setFloat = function (uniform, value) {
  98870. };
  98871. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  98872. };
  98873. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  98874. };
  98875. NullEngine.prototype.setBool = function (uniform, bool) {
  98876. };
  98877. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  98878. };
  98879. NullEngine.prototype.setColor3 = function (uniform, color3) {
  98880. };
  98881. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  98882. };
  98883. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  98884. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  98885. if (this._alphaMode === mode) {
  98886. return;
  98887. }
  98888. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  98889. if (!noDepthWriteChange) {
  98890. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  98891. }
  98892. this._alphaMode = mode;
  98893. };
  98894. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  98895. };
  98896. NullEngine.prototype.wipeCaches = function (bruteForce) {
  98897. if (this.preventCacheWipeBetweenFrames) {
  98898. return;
  98899. }
  98900. this.resetTextureCache();
  98901. this._currentEffect = null;
  98902. if (bruteForce) {
  98903. this._currentProgram = null;
  98904. this._stencilState.reset();
  98905. this._depthCullingState.reset();
  98906. this._alphaState.reset();
  98907. }
  98908. this._cachedVertexBuffers = null;
  98909. this._cachedIndexBuffer = null;
  98910. this._cachedEffectForVertexBuffers = null;
  98911. };
  98912. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  98913. };
  98914. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  98915. };
  98916. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  98917. };
  98918. NullEngine.prototype._createTexture = function () {
  98919. return {};
  98920. };
  98921. NullEngine.prototype._releaseTexture = function (texture) {
  98922. };
  98923. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  98924. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98925. if (onLoad === void 0) { onLoad = null; }
  98926. if (onError === void 0) { onError = null; }
  98927. if (buffer === void 0) { buffer = null; }
  98928. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  98929. var url = String(urlArg);
  98930. texture.url = url;
  98931. texture.generateMipMaps = !noMipmap;
  98932. texture.samplingMode = samplingMode;
  98933. texture.invertY = invertY;
  98934. texture.baseWidth = this._options.textureSize;
  98935. texture.baseHeight = this._options.textureSize;
  98936. texture.width = this._options.textureSize;
  98937. texture.height = this._options.textureSize;
  98938. if (format) {
  98939. texture.format = format;
  98940. }
  98941. texture.isReady = true;
  98942. if (onLoad) {
  98943. onLoad();
  98944. }
  98945. this._internalTexturesCache.push(texture);
  98946. return texture;
  98947. };
  98948. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  98949. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  98950. if (options !== undefined && typeof options === "object") {
  98951. fullOptions.generateMipMaps = options.generateMipMaps;
  98952. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  98953. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  98954. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  98955. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  98956. }
  98957. else {
  98958. fullOptions.generateMipMaps = options;
  98959. fullOptions.generateDepthBuffer = true;
  98960. fullOptions.generateStencilBuffer = false;
  98961. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98962. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  98963. }
  98964. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  98965. var width = size.width || size;
  98966. var height = size.height || size;
  98967. texture._depthStencilBuffer = {};
  98968. texture._framebuffer = {};
  98969. texture.baseWidth = width;
  98970. texture.baseHeight = height;
  98971. texture.width = width;
  98972. texture.height = height;
  98973. texture.isReady = true;
  98974. texture.samples = 1;
  98975. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  98976. texture.samplingMode = fullOptions.samplingMode;
  98977. texture.type = fullOptions.type;
  98978. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  98979. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  98980. this._internalTexturesCache.push(texture);
  98981. return texture;
  98982. };
  98983. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  98984. texture.samplingMode = samplingMode;
  98985. };
  98986. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  98987. if (this._currentRenderTarget) {
  98988. this.unBindFramebuffer(this._currentRenderTarget);
  98989. }
  98990. this._currentRenderTarget = texture;
  98991. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  98992. if (this._cachedViewport && !forceFullscreenViewport) {
  98993. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  98994. }
  98995. };
  98996. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  98997. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  98998. this._currentRenderTarget = null;
  98999. if (onBeforeUnbind) {
  99000. if (texture._MSAAFramebuffer) {
  99001. this._currentFramebuffer = texture._framebuffer;
  99002. }
  99003. onBeforeUnbind();
  99004. }
  99005. this._currentFramebuffer = null;
  99006. };
  99007. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  99008. var vbo = {
  99009. capacity: 1,
  99010. references: 1,
  99011. is32Bits: false
  99012. };
  99013. return vbo;
  99014. };
  99015. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  99016. if (offset === void 0) { offset = 0; }
  99017. };
  99018. /**
  99019. * Updates a dynamic vertex buffer.
  99020. * @param vertexBuffer the vertex buffer to update
  99021. * @param data the data used to update the vertex buffer
  99022. * @param byteOffset the byte offset of the data (optional)
  99023. * @param byteLength the byte length of the data (optional)
  99024. */
  99025. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  99026. };
  99027. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  99028. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  99029. this._boundTexturesCache[this._activeChannel] = texture;
  99030. return true;
  99031. }
  99032. return false;
  99033. };
  99034. NullEngine.prototype._bindTexture = function (channel, texture) {
  99035. if (channel < 0) {
  99036. return;
  99037. }
  99038. this._bindTextureDirectly(0, texture);
  99039. };
  99040. NullEngine.prototype._releaseBuffer = function (buffer) {
  99041. buffer.references--;
  99042. if (buffer.references === 0) {
  99043. return true;
  99044. }
  99045. return false;
  99046. };
  99047. NullEngine.prototype.releaseEffects = function () {
  99048. };
  99049. return NullEngine;
  99050. }(BABYLON.Engine));
  99051. BABYLON.NullEngine = NullEngine;
  99052. })(BABYLON || (BABYLON = {}));
  99053. //# sourceMappingURL=babylon.nullEngine.js.map
  99054. var BABYLON;
  99055. (function (BABYLON) {
  99056. /**
  99057. * This class can be used to get instrumentation data from a Babylon engine
  99058. */
  99059. var EngineInstrumentation = /** @class */ (function () {
  99060. function EngineInstrumentation(engine) {
  99061. this.engine = engine;
  99062. this._captureGPUFrameTime = false;
  99063. this._gpuFrameTime = new BABYLON.PerfCounter();
  99064. this._captureShaderCompilationTime = false;
  99065. this._shaderCompilationTime = new BABYLON.PerfCounter();
  99066. // Observers
  99067. this._onBeginFrameObserver = null;
  99068. this._onEndFrameObserver = null;
  99069. this._onBeforeShaderCompilationObserver = null;
  99070. this._onAfterShaderCompilationObserver = null;
  99071. }
  99072. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  99073. // Properties
  99074. /**
  99075. * Gets the perf counter used for GPU frame time
  99076. */
  99077. get: function () {
  99078. return this._gpuFrameTime;
  99079. },
  99080. enumerable: true,
  99081. configurable: true
  99082. });
  99083. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  99084. /**
  99085. * Gets the GPU frame time capture status
  99086. */
  99087. get: function () {
  99088. return this._captureGPUFrameTime;
  99089. },
  99090. /**
  99091. * Enable or disable the GPU frame time capture
  99092. */
  99093. set: function (value) {
  99094. var _this = this;
  99095. if (value === this._captureGPUFrameTime) {
  99096. return;
  99097. }
  99098. this._captureGPUFrameTime = value;
  99099. if (value) {
  99100. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  99101. if (!_this._gpuFrameTimeToken) {
  99102. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  99103. }
  99104. });
  99105. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  99106. if (!_this._gpuFrameTimeToken) {
  99107. return;
  99108. }
  99109. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  99110. if (time > -1) {
  99111. _this._gpuFrameTimeToken = null;
  99112. _this._gpuFrameTime.fetchNewFrame();
  99113. _this._gpuFrameTime.addCount(time, true);
  99114. }
  99115. });
  99116. }
  99117. else {
  99118. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  99119. this._onBeginFrameObserver = null;
  99120. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  99121. this._onEndFrameObserver = null;
  99122. }
  99123. },
  99124. enumerable: true,
  99125. configurable: true
  99126. });
  99127. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  99128. /**
  99129. * Gets the perf counter used for shader compilation time
  99130. */
  99131. get: function () {
  99132. return this._shaderCompilationTime;
  99133. },
  99134. enumerable: true,
  99135. configurable: true
  99136. });
  99137. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  99138. /**
  99139. * Gets the shader compilation time capture status
  99140. */
  99141. get: function () {
  99142. return this._captureShaderCompilationTime;
  99143. },
  99144. /**
  99145. * Enable or disable the shader compilation time capture
  99146. */
  99147. set: function (value) {
  99148. var _this = this;
  99149. if (value === this._captureShaderCompilationTime) {
  99150. return;
  99151. }
  99152. this._captureShaderCompilationTime = value;
  99153. if (value) {
  99154. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  99155. _this._shaderCompilationTime.fetchNewFrame();
  99156. _this._shaderCompilationTime.beginMonitoring();
  99157. });
  99158. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  99159. _this._shaderCompilationTime.endMonitoring();
  99160. });
  99161. }
  99162. else {
  99163. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  99164. this._onBeforeShaderCompilationObserver = null;
  99165. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  99166. this._onAfterShaderCompilationObserver = null;
  99167. }
  99168. },
  99169. enumerable: true,
  99170. configurable: true
  99171. });
  99172. EngineInstrumentation.prototype.dispose = function () {
  99173. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  99174. this._onBeginFrameObserver = null;
  99175. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  99176. this._onEndFrameObserver = null;
  99177. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  99178. this._onBeforeShaderCompilationObserver = null;
  99179. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  99180. this._onAfterShaderCompilationObserver = null;
  99181. this.engine = null;
  99182. };
  99183. return EngineInstrumentation;
  99184. }());
  99185. BABYLON.EngineInstrumentation = EngineInstrumentation;
  99186. })(BABYLON || (BABYLON = {}));
  99187. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  99188. var BABYLON;
  99189. (function (BABYLON) {
  99190. /**
  99191. * This class can be used to get instrumentation data from a Babylon engine
  99192. */
  99193. var SceneInstrumentation = /** @class */ (function () {
  99194. function SceneInstrumentation(scene) {
  99195. var _this = this;
  99196. this.scene = scene;
  99197. this._captureActiveMeshesEvaluationTime = false;
  99198. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  99199. this._captureRenderTargetsRenderTime = false;
  99200. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  99201. this._captureFrameTime = false;
  99202. this._frameTime = new BABYLON.PerfCounter();
  99203. this._captureRenderTime = false;
  99204. this._renderTime = new BABYLON.PerfCounter();
  99205. this._captureInterFrameTime = false;
  99206. this._interFrameTime = new BABYLON.PerfCounter();
  99207. this._captureParticlesRenderTime = false;
  99208. this._particlesRenderTime = new BABYLON.PerfCounter();
  99209. this._captureSpritesRenderTime = false;
  99210. this._spritesRenderTime = new BABYLON.PerfCounter();
  99211. this._capturePhysicsTime = false;
  99212. this._physicsTime = new BABYLON.PerfCounter();
  99213. this._captureAnimationsTime = false;
  99214. this._animationsTime = new BABYLON.PerfCounter();
  99215. this._captureCameraRenderTime = false;
  99216. this._cameraRenderTime = new BABYLON.PerfCounter();
  99217. // Observers
  99218. this._onBeforeActiveMeshesEvaluationObserver = null;
  99219. this._onAfterActiveMeshesEvaluationObserver = null;
  99220. this._onBeforeRenderTargetsRenderObserver = null;
  99221. this._onAfterRenderTargetsRenderObserver = null;
  99222. this._onAfterRenderObserver = null;
  99223. this._onBeforeDrawPhaseObserver = null;
  99224. this._onAfterDrawPhaseObserver = null;
  99225. this._onBeforeAnimationsObserver = null;
  99226. this._onBeforeParticlesRenderingObserver = null;
  99227. this._onAfterParticlesRenderingObserver = null;
  99228. this._onBeforeSpritesRenderingObserver = null;
  99229. this._onAfterSpritesRenderingObserver = null;
  99230. this._onBeforePhysicsObserver = null;
  99231. this._onAfterPhysicsObserver = null;
  99232. this._onAfterAnimationsObserver = null;
  99233. this._onBeforeCameraRenderObserver = null;
  99234. this._onAfterCameraRenderObserver = null;
  99235. // Before render
  99236. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  99237. if (_this._captureActiveMeshesEvaluationTime) {
  99238. _this._activeMeshesEvaluationTime.fetchNewFrame();
  99239. }
  99240. if (_this._captureRenderTargetsRenderTime) {
  99241. _this._renderTargetsRenderTime.fetchNewFrame();
  99242. }
  99243. if (_this._captureFrameTime) {
  99244. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  99245. _this._frameTime.beginMonitoring();
  99246. }
  99247. if (_this._captureInterFrameTime) {
  99248. _this._interFrameTime.endMonitoring();
  99249. }
  99250. if (_this._captureParticlesRenderTime) {
  99251. _this._particlesRenderTime.fetchNewFrame();
  99252. }
  99253. if (_this._captureSpritesRenderTime) {
  99254. _this._spritesRenderTime.fetchNewFrame();
  99255. }
  99256. if (_this._captureAnimationsTime) {
  99257. _this._animationsTime.beginMonitoring();
  99258. }
  99259. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  99260. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  99261. });
  99262. // After render
  99263. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  99264. if (_this._captureFrameTime) {
  99265. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  99266. _this._frameTime.endMonitoring();
  99267. }
  99268. if (_this._captureRenderTime) {
  99269. _this._renderTime.endMonitoring(false);
  99270. }
  99271. if (_this._captureInterFrameTime) {
  99272. _this._interFrameTime.beginMonitoring();
  99273. }
  99274. });
  99275. }
  99276. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  99277. // Properties
  99278. /**
  99279. * Gets the perf counter used for active meshes evaluation time
  99280. */
  99281. get: function () {
  99282. return this._activeMeshesEvaluationTime;
  99283. },
  99284. enumerable: true,
  99285. configurable: true
  99286. });
  99287. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  99288. /**
  99289. * Gets the active meshes evaluation time capture status
  99290. */
  99291. get: function () {
  99292. return this._captureActiveMeshesEvaluationTime;
  99293. },
  99294. /**
  99295. * Enable or disable the active meshes evaluation time capture
  99296. */
  99297. set: function (value) {
  99298. var _this = this;
  99299. if (value === this._captureActiveMeshesEvaluationTime) {
  99300. return;
  99301. }
  99302. this._captureActiveMeshesEvaluationTime = value;
  99303. if (value) {
  99304. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  99305. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  99306. _this._activeMeshesEvaluationTime.beginMonitoring();
  99307. });
  99308. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  99309. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  99310. _this._activeMeshesEvaluationTime.endMonitoring();
  99311. });
  99312. }
  99313. else {
  99314. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  99315. this._onBeforeActiveMeshesEvaluationObserver = null;
  99316. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  99317. this._onAfterActiveMeshesEvaluationObserver = null;
  99318. }
  99319. },
  99320. enumerable: true,
  99321. configurable: true
  99322. });
  99323. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  99324. /**
  99325. * Gets the perf counter used for render targets render time
  99326. */
  99327. get: function () {
  99328. return this._renderTargetsRenderTime;
  99329. },
  99330. enumerable: true,
  99331. configurable: true
  99332. });
  99333. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  99334. /**
  99335. * Gets the render targets render time capture status
  99336. */
  99337. get: function () {
  99338. return this._captureRenderTargetsRenderTime;
  99339. },
  99340. /**
  99341. * Enable or disable the render targets render time capture
  99342. */
  99343. set: function (value) {
  99344. var _this = this;
  99345. if (value === this._captureRenderTargetsRenderTime) {
  99346. return;
  99347. }
  99348. this._captureRenderTargetsRenderTime = value;
  99349. if (value) {
  99350. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  99351. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  99352. _this._renderTargetsRenderTime.beginMonitoring();
  99353. });
  99354. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  99355. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  99356. _this._renderTargetsRenderTime.endMonitoring(false);
  99357. });
  99358. }
  99359. else {
  99360. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  99361. this._onBeforeRenderTargetsRenderObserver = null;
  99362. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  99363. this._onAfterRenderTargetsRenderObserver = null;
  99364. }
  99365. },
  99366. enumerable: true,
  99367. configurable: true
  99368. });
  99369. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  99370. /**
  99371. * Gets the perf counter used for particles render time
  99372. */
  99373. get: function () {
  99374. return this._particlesRenderTime;
  99375. },
  99376. enumerable: true,
  99377. configurable: true
  99378. });
  99379. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  99380. /**
  99381. * Gets the particles render time capture status
  99382. */
  99383. get: function () {
  99384. return this._captureParticlesRenderTime;
  99385. },
  99386. /**
  99387. * Enable or disable the particles render time capture
  99388. */
  99389. set: function (value) {
  99390. var _this = this;
  99391. if (value === this._captureParticlesRenderTime) {
  99392. return;
  99393. }
  99394. this._captureParticlesRenderTime = value;
  99395. if (value) {
  99396. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  99397. BABYLON.Tools.StartPerformanceCounter("Particles");
  99398. _this._particlesRenderTime.beginMonitoring();
  99399. });
  99400. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  99401. BABYLON.Tools.EndPerformanceCounter("Particles");
  99402. _this._particlesRenderTime.endMonitoring(false);
  99403. });
  99404. }
  99405. else {
  99406. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  99407. this._onBeforeParticlesRenderingObserver = null;
  99408. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  99409. this._onAfterParticlesRenderingObserver = null;
  99410. }
  99411. },
  99412. enumerable: true,
  99413. configurable: true
  99414. });
  99415. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  99416. /**
  99417. * Gets the perf counter used for sprites render time
  99418. */
  99419. get: function () {
  99420. return this._spritesRenderTime;
  99421. },
  99422. enumerable: true,
  99423. configurable: true
  99424. });
  99425. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  99426. /**
  99427. * Gets the sprites render time capture status
  99428. */
  99429. get: function () {
  99430. return this._captureSpritesRenderTime;
  99431. },
  99432. /**
  99433. * Enable or disable the sprites render time capture
  99434. */
  99435. set: function (value) {
  99436. var _this = this;
  99437. if (value === this._captureSpritesRenderTime) {
  99438. return;
  99439. }
  99440. this._captureSpritesRenderTime = value;
  99441. if (value) {
  99442. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  99443. BABYLON.Tools.StartPerformanceCounter("Sprites");
  99444. _this._spritesRenderTime.beginMonitoring();
  99445. });
  99446. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  99447. BABYLON.Tools.EndPerformanceCounter("Sprites");
  99448. _this._spritesRenderTime.endMonitoring(false);
  99449. });
  99450. }
  99451. else {
  99452. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  99453. this._onBeforeSpritesRenderingObserver = null;
  99454. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  99455. this._onAfterSpritesRenderingObserver = null;
  99456. }
  99457. },
  99458. enumerable: true,
  99459. configurable: true
  99460. });
  99461. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  99462. /**
  99463. * Gets the perf counter used for physics time
  99464. */
  99465. get: function () {
  99466. return this._physicsTime;
  99467. },
  99468. enumerable: true,
  99469. configurable: true
  99470. });
  99471. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  99472. /**
  99473. * Gets the physics time capture status
  99474. */
  99475. get: function () {
  99476. return this._capturePhysicsTime;
  99477. },
  99478. /**
  99479. * Enable or disable the physics time capture
  99480. */
  99481. set: function (value) {
  99482. var _this = this;
  99483. if (value === this._capturePhysicsTime) {
  99484. return;
  99485. }
  99486. this._capturePhysicsTime = value;
  99487. if (value) {
  99488. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  99489. BABYLON.Tools.StartPerformanceCounter("Physics");
  99490. _this._physicsTime.beginMonitoring();
  99491. });
  99492. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  99493. BABYLON.Tools.EndPerformanceCounter("Physics");
  99494. _this._physicsTime.endMonitoring();
  99495. });
  99496. }
  99497. else {
  99498. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  99499. this._onBeforePhysicsObserver = null;
  99500. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  99501. this._onAfterPhysicsObserver = null;
  99502. }
  99503. },
  99504. enumerable: true,
  99505. configurable: true
  99506. });
  99507. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  99508. /**
  99509. * Gets the perf counter used for animations time
  99510. */
  99511. get: function () {
  99512. return this._animationsTime;
  99513. },
  99514. enumerable: true,
  99515. configurable: true
  99516. });
  99517. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  99518. /**
  99519. * Gets the animations time capture status
  99520. */
  99521. get: function () {
  99522. return this._captureAnimationsTime;
  99523. },
  99524. /**
  99525. * Enable or disable the animations time capture
  99526. */
  99527. set: function (value) {
  99528. var _this = this;
  99529. if (value === this._captureAnimationsTime) {
  99530. return;
  99531. }
  99532. this._captureAnimationsTime = value;
  99533. if (value) {
  99534. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  99535. _this._animationsTime.endMonitoring();
  99536. });
  99537. }
  99538. else {
  99539. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  99540. this._onAfterAnimationsObserver = null;
  99541. }
  99542. },
  99543. enumerable: true,
  99544. configurable: true
  99545. });
  99546. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  99547. /**
  99548. * Gets the perf counter used for frame time capture
  99549. */
  99550. get: function () {
  99551. return this._frameTime;
  99552. },
  99553. enumerable: true,
  99554. configurable: true
  99555. });
  99556. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  99557. /**
  99558. * Gets the frame time capture status
  99559. */
  99560. get: function () {
  99561. return this._captureFrameTime;
  99562. },
  99563. /**
  99564. * Enable or disable the frame time capture
  99565. */
  99566. set: function (value) {
  99567. this._captureFrameTime = value;
  99568. },
  99569. enumerable: true,
  99570. configurable: true
  99571. });
  99572. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  99573. /**
  99574. * Gets the perf counter used for inter-frames time capture
  99575. */
  99576. get: function () {
  99577. return this._interFrameTime;
  99578. },
  99579. enumerable: true,
  99580. configurable: true
  99581. });
  99582. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  99583. /**
  99584. * Gets the inter-frames time capture status
  99585. */
  99586. get: function () {
  99587. return this._captureInterFrameTime;
  99588. },
  99589. /**
  99590. * Enable or disable the inter-frames time capture
  99591. */
  99592. set: function (value) {
  99593. this._captureInterFrameTime = value;
  99594. },
  99595. enumerable: true,
  99596. configurable: true
  99597. });
  99598. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  99599. /**
  99600. * Gets the perf counter used for render time capture
  99601. */
  99602. get: function () {
  99603. return this._renderTime;
  99604. },
  99605. enumerable: true,
  99606. configurable: true
  99607. });
  99608. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  99609. /**
  99610. * Gets the render time capture status
  99611. */
  99612. get: function () {
  99613. return this._captureRenderTime;
  99614. },
  99615. /**
  99616. * Enable or disable the render time capture
  99617. */
  99618. set: function (value) {
  99619. var _this = this;
  99620. if (value === this._captureRenderTime) {
  99621. return;
  99622. }
  99623. this._captureRenderTime = value;
  99624. if (value) {
  99625. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  99626. _this._renderTime.beginMonitoring();
  99627. BABYLON.Tools.StartPerformanceCounter("Main render");
  99628. });
  99629. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  99630. _this._renderTime.endMonitoring(false);
  99631. BABYLON.Tools.EndPerformanceCounter("Main render");
  99632. });
  99633. }
  99634. else {
  99635. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  99636. this._onBeforeDrawPhaseObserver = null;
  99637. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  99638. this._onAfterDrawPhaseObserver = null;
  99639. }
  99640. },
  99641. enumerable: true,
  99642. configurable: true
  99643. });
  99644. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  99645. /**
  99646. * Gets the perf counter used for camera render time capture
  99647. */
  99648. get: function () {
  99649. return this._cameraRenderTime;
  99650. },
  99651. enumerable: true,
  99652. configurable: true
  99653. });
  99654. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  99655. /**
  99656. * Gets the camera render time capture status
  99657. */
  99658. get: function () {
  99659. return this._captureCameraRenderTime;
  99660. },
  99661. /**
  99662. * Enable or disable the camera render time capture
  99663. */
  99664. set: function (value) {
  99665. var _this = this;
  99666. if (value === this._captureCameraRenderTime) {
  99667. return;
  99668. }
  99669. this._captureCameraRenderTime = value;
  99670. if (value) {
  99671. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  99672. _this._cameraRenderTime.beginMonitoring();
  99673. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  99674. });
  99675. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  99676. _this._cameraRenderTime.endMonitoring(false);
  99677. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  99678. });
  99679. }
  99680. else {
  99681. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  99682. this._onBeforeCameraRenderObserver = null;
  99683. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  99684. this._onAfterCameraRenderObserver = null;
  99685. }
  99686. },
  99687. enumerable: true,
  99688. configurable: true
  99689. });
  99690. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  99691. /**
  99692. * Gets the perf counter used for draw calls
  99693. */
  99694. get: function () {
  99695. return this.scene.getEngine()._drawCalls;
  99696. },
  99697. enumerable: true,
  99698. configurable: true
  99699. });
  99700. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  99701. /**
  99702. * Gets the perf counter used for texture collisions
  99703. */
  99704. get: function () {
  99705. return this.scene.getEngine()._textureCollisions;
  99706. },
  99707. enumerable: true,
  99708. configurable: true
  99709. });
  99710. SceneInstrumentation.prototype.dispose = function () {
  99711. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  99712. this._onAfterRenderObserver = null;
  99713. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  99714. this._onBeforeActiveMeshesEvaluationObserver = null;
  99715. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  99716. this._onAfterActiveMeshesEvaluationObserver = null;
  99717. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  99718. this._onBeforeRenderTargetsRenderObserver = null;
  99719. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  99720. this._onAfterRenderTargetsRenderObserver = null;
  99721. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  99722. this._onBeforeAnimationsObserver = null;
  99723. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  99724. this._onBeforeParticlesRenderingObserver = null;
  99725. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  99726. this._onAfterParticlesRenderingObserver = null;
  99727. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  99728. this._onBeforeSpritesRenderingObserver = null;
  99729. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  99730. this._onAfterSpritesRenderingObserver = null;
  99731. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  99732. this._onBeforeDrawPhaseObserver = null;
  99733. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  99734. this._onAfterDrawPhaseObserver = null;
  99735. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  99736. this._onBeforePhysicsObserver = null;
  99737. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  99738. this._onAfterPhysicsObserver = null;
  99739. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  99740. this._onAfterAnimationsObserver = null;
  99741. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  99742. this._onBeforeCameraRenderObserver = null;
  99743. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  99744. this._onAfterCameraRenderObserver = null;
  99745. this.scene = null;
  99746. };
  99747. return SceneInstrumentation;
  99748. }());
  99749. BABYLON.SceneInstrumentation = SceneInstrumentation;
  99750. })(BABYLON || (BABYLON = {}));
  99751. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  99752. var BABYLON;
  99753. (function (BABYLON) {
  99754. /**
  99755. * @hidden
  99756. **/
  99757. var _TimeToken = /** @class */ (function () {
  99758. function _TimeToken() {
  99759. this._timeElapsedQueryEnded = false;
  99760. }
  99761. return _TimeToken;
  99762. }());
  99763. BABYLON._TimeToken = _TimeToken;
  99764. })(BABYLON || (BABYLON = {}));
  99765. //# sourceMappingURL=babylon.timeToken.js.map
  99766. var BABYLON;
  99767. (function (BABYLON) {
  99768. /**
  99769. * Background material defines definition.
  99770. * @hidden Mainly internal Use
  99771. */
  99772. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  99773. __extends(BackgroundMaterialDefines, _super);
  99774. /**
  99775. * Constructor of the defines.
  99776. */
  99777. function BackgroundMaterialDefines() {
  99778. var _this = _super.call(this) || this;
  99779. /**
  99780. * True if the diffuse texture is in use.
  99781. */
  99782. _this.DIFFUSE = false;
  99783. /**
  99784. * The direct UV channel to use.
  99785. */
  99786. _this.DIFFUSEDIRECTUV = 0;
  99787. /**
  99788. * True if the diffuse texture is in gamma space.
  99789. */
  99790. _this.GAMMADIFFUSE = false;
  99791. /**
  99792. * True if the diffuse texture has opacity in the alpha channel.
  99793. */
  99794. _this.DIFFUSEHASALPHA = false;
  99795. /**
  99796. * True if you want the material to fade to transparent at grazing angle.
  99797. */
  99798. _this.OPACITYFRESNEL = false;
  99799. /**
  99800. * True if an extra blur needs to be added in the reflection.
  99801. */
  99802. _this.REFLECTIONBLUR = false;
  99803. /**
  99804. * True if you want the material to fade to reflection at grazing angle.
  99805. */
  99806. _this.REFLECTIONFRESNEL = false;
  99807. /**
  99808. * True if you want the material to falloff as far as you move away from the scene center.
  99809. */
  99810. _this.REFLECTIONFALLOFF = false;
  99811. /**
  99812. * False if the current Webgl implementation does not support the texture lod extension.
  99813. */
  99814. _this.TEXTURELODSUPPORT = false;
  99815. /**
  99816. * True to ensure the data are premultiplied.
  99817. */
  99818. _this.PREMULTIPLYALPHA = false;
  99819. /**
  99820. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  99821. */
  99822. _this.USERGBCOLOR = false;
  99823. /**
  99824. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  99825. * stays aligned with the desired configuration.
  99826. */
  99827. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  99828. /**
  99829. * True to add noise in order to reduce the banding effect.
  99830. */
  99831. _this.NOISE = false;
  99832. /**
  99833. * is the reflection texture in BGR color scheme?
  99834. * Mainly used to solve a bug in ios10 video tag
  99835. */
  99836. _this.REFLECTIONBGR = false;
  99837. _this.IMAGEPROCESSING = false;
  99838. _this.VIGNETTE = false;
  99839. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  99840. _this.VIGNETTEBLENDMODEOPAQUE = false;
  99841. _this.TONEMAPPING = false;
  99842. _this.CONTRAST = false;
  99843. _this.COLORCURVES = false;
  99844. _this.COLORGRADING = false;
  99845. _this.COLORGRADING3D = false;
  99846. _this.SAMPLER3DGREENDEPTH = false;
  99847. _this.SAMPLER3DBGRMAP = false;
  99848. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  99849. _this.EXPOSURE = false;
  99850. // Reflection.
  99851. _this.REFLECTION = false;
  99852. _this.REFLECTIONMAP_3D = false;
  99853. _this.REFLECTIONMAP_SPHERICAL = false;
  99854. _this.REFLECTIONMAP_PLANAR = false;
  99855. _this.REFLECTIONMAP_CUBIC = false;
  99856. _this.REFLECTIONMAP_PROJECTION = false;
  99857. _this.REFLECTIONMAP_SKYBOX = false;
  99858. _this.REFLECTIONMAP_EXPLICIT = false;
  99859. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  99860. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  99861. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  99862. _this.INVERTCUBICMAP = false;
  99863. _this.REFLECTIONMAP_OPPOSITEZ = false;
  99864. _this.LODINREFLECTIONALPHA = false;
  99865. _this.GAMMAREFLECTION = false;
  99866. _this.RGBDREFLECTION = false;
  99867. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  99868. // Default BJS.
  99869. _this.MAINUV1 = false;
  99870. _this.MAINUV2 = false;
  99871. _this.UV1 = false;
  99872. _this.UV2 = false;
  99873. _this.CLIPPLANE = false;
  99874. _this.POINTSIZE = false;
  99875. _this.FOG = false;
  99876. _this.NORMAL = false;
  99877. _this.NUM_BONE_INFLUENCERS = 0;
  99878. _this.BonesPerMesh = 0;
  99879. _this.INSTANCES = false;
  99880. _this.SHADOWFLOAT = false;
  99881. _this.rebuild();
  99882. return _this;
  99883. }
  99884. return BackgroundMaterialDefines;
  99885. }(BABYLON.MaterialDefines));
  99886. /**
  99887. * Background material used to create an efficient environement around your scene.
  99888. */
  99889. var BackgroundMaterial = /** @class */ (function (_super) {
  99890. __extends(BackgroundMaterial, _super);
  99891. /**
  99892. * Instantiates a Background Material in the given scene
  99893. * @param name The friendly name of the material
  99894. * @param scene The scene to add the material to
  99895. */
  99896. function BackgroundMaterial(name, scene) {
  99897. var _this = _super.call(this, name, scene) || this;
  99898. /**
  99899. * Key light Color (multiply against the environement texture)
  99900. */
  99901. _this.primaryColor = BABYLON.Color3.White();
  99902. _this._primaryColorShadowLevel = 0;
  99903. _this._primaryColorHighlightLevel = 0;
  99904. /**
  99905. * Reflection Texture used in the material.
  99906. * Should be author in a specific way for the best result (refer to the documentation).
  99907. */
  99908. _this.reflectionTexture = null;
  99909. /**
  99910. * Reflection Texture level of blur.
  99911. *
  99912. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  99913. * texture twice.
  99914. */
  99915. _this.reflectionBlur = 0;
  99916. /**
  99917. * Diffuse Texture used in the material.
  99918. * Should be author in a specific way for the best result (refer to the documentation).
  99919. */
  99920. _this.diffuseTexture = null;
  99921. _this._shadowLights = null;
  99922. /**
  99923. * Specify the list of lights casting shadow on the material.
  99924. * All scene shadow lights will be included if null.
  99925. */
  99926. _this.shadowLights = null;
  99927. /**
  99928. * Helps adjusting the shadow to a softer level if required.
  99929. * 0 means black shadows and 1 means no shadows.
  99930. */
  99931. _this.shadowLevel = 0;
  99932. /**
  99933. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  99934. * It is usually zero but might be interesting to modify according to your setup.
  99935. */
  99936. _this.sceneCenter = BABYLON.Vector3.Zero();
  99937. /**
  99938. * This helps specifying that the material is falling off to the sky box at grazing angle.
  99939. * This helps ensuring a nice transition when the camera goes under the ground.
  99940. */
  99941. _this.opacityFresnel = true;
  99942. /**
  99943. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  99944. * This helps adding a mirror texture on the ground.
  99945. */
  99946. _this.reflectionFresnel = false;
  99947. /**
  99948. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  99949. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  99950. */
  99951. _this.reflectionFalloffDistance = 0.0;
  99952. /**
  99953. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  99954. */
  99955. _this.reflectionAmount = 1.0;
  99956. /**
  99957. * This specifies the weight of the reflection at grazing angle.
  99958. */
  99959. _this.reflectionReflectance0 = 0.05;
  99960. /**
  99961. * This specifies the weight of the reflection at a perpendicular point of view.
  99962. */
  99963. _this.reflectionReflectance90 = 0.5;
  99964. /**
  99965. * Helps to directly use the maps channels instead of their level.
  99966. */
  99967. _this.useRGBColor = true;
  99968. /**
  99969. * This helps reducing the banding effect that could occur on the background.
  99970. */
  99971. _this.enableNoise = false;
  99972. _this._fovMultiplier = 1.0;
  99973. /**
  99974. * Enable the FOV adjustment feature controlled by fovMultiplier.
  99975. */
  99976. _this.useEquirectangularFOV = false;
  99977. _this._maxSimultaneousLights = 4;
  99978. /**
  99979. * Number of Simultaneous lights allowed on the material.
  99980. */
  99981. _this.maxSimultaneousLights = 4;
  99982. /**
  99983. * Keep track of the image processing observer to allow dispose and replace.
  99984. */
  99985. _this._imageProcessingObserver = null;
  99986. /**
  99987. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  99988. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  99989. */
  99990. _this.switchToBGR = false;
  99991. // Temp values kept as cache in the material.
  99992. _this._renderTargets = new BABYLON.SmartArray(16);
  99993. _this._reflectionControls = BABYLON.Vector4.Zero();
  99994. _this._white = BABYLON.Color3.White();
  99995. _this._primaryShadowColor = BABYLON.Color3.Black();
  99996. _this._primaryHighlightColor = BABYLON.Color3.Black();
  99997. // Setup the default processing configuration to the scene.
  99998. _this._attachImageProcessingConfiguration(null);
  99999. _this.getRenderTargetTextures = function () {
  100000. _this._renderTargets.reset();
  100001. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  100002. _this._renderTargets.push(_this._diffuseTexture);
  100003. }
  100004. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  100005. _this._renderTargets.push(_this._reflectionTexture);
  100006. }
  100007. return _this._renderTargets;
  100008. };
  100009. return _this;
  100010. }
  100011. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  100012. /**
  100013. * Experimental Internal Use Only.
  100014. *
  100015. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  100016. * This acts as a helper to set the primary color to a more "human friendly" value.
  100017. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  100018. * output color as close as possible from the chosen value.
  100019. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  100020. * part of lighting setup.)
  100021. */
  100022. get: function () {
  100023. return this.__perceptualColor;
  100024. },
  100025. set: function (value) {
  100026. this.__perceptualColor = value;
  100027. this._computePrimaryColorFromPerceptualColor();
  100028. this._markAllSubMeshesAsLightsDirty();
  100029. },
  100030. enumerable: true,
  100031. configurable: true
  100032. });
  100033. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  100034. /**
  100035. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  100036. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  100037. */
  100038. get: function () {
  100039. return this._primaryColorShadowLevel;
  100040. },
  100041. set: function (value) {
  100042. this._primaryColorShadowLevel = value;
  100043. this._computePrimaryColors();
  100044. this._markAllSubMeshesAsLightsDirty();
  100045. },
  100046. enumerable: true,
  100047. configurable: true
  100048. });
  100049. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  100050. /**
  100051. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  100052. * The primary color is used at the level chosen to define what the white area would look.
  100053. */
  100054. get: function () {
  100055. return this._primaryColorHighlightLevel;
  100056. },
  100057. set: function (value) {
  100058. this._primaryColorHighlightLevel = value;
  100059. this._computePrimaryColors();
  100060. this._markAllSubMeshesAsLightsDirty();
  100061. },
  100062. enumerable: true,
  100063. configurable: true
  100064. });
  100065. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  100066. /**
  100067. * Sets the reflection reflectance fresnel values according to the default standard
  100068. * empirically know to work well :-)
  100069. */
  100070. set: function (value) {
  100071. var reflectionWeight = value;
  100072. if (reflectionWeight < 0.5) {
  100073. reflectionWeight = reflectionWeight * 2.0;
  100074. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  100075. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  100076. }
  100077. else {
  100078. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  100079. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  100080. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  100081. }
  100082. },
  100083. enumerable: true,
  100084. configurable: true
  100085. });
  100086. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  100087. /**
  100088. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100089. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  100090. * Recommended to be keep at 1.0 except for special cases.
  100091. */
  100092. get: function () {
  100093. return this._fovMultiplier;
  100094. },
  100095. set: function (value) {
  100096. if (isNaN(value)) {
  100097. value = 1.0;
  100098. }
  100099. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  100100. },
  100101. enumerable: true,
  100102. configurable: true
  100103. });
  100104. /**
  100105. * Attaches a new image processing configuration to the PBR Material.
  100106. * @param configuration (if null the scene configuration will be use)
  100107. */
  100108. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  100109. var _this = this;
  100110. if (configuration === this._imageProcessingConfiguration) {
  100111. return;
  100112. }
  100113. // Detaches observer.
  100114. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  100115. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  100116. }
  100117. // Pick the scene configuration if needed.
  100118. if (!configuration) {
  100119. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  100120. }
  100121. else {
  100122. this._imageProcessingConfiguration = configuration;
  100123. }
  100124. // Attaches observer.
  100125. if (this._imageProcessingConfiguration) {
  100126. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  100127. _this._computePrimaryColorFromPerceptualColor();
  100128. _this._markAllSubMeshesAsImageProcessingDirty();
  100129. });
  100130. }
  100131. };
  100132. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  100133. /**
  100134. * Gets the image processing configuration used either in this material.
  100135. */
  100136. get: function () {
  100137. return this._imageProcessingConfiguration;
  100138. },
  100139. /**
  100140. * Sets the Default image processing configuration used either in the this material.
  100141. *
  100142. * If sets to null, the scene one is in use.
  100143. */
  100144. set: function (value) {
  100145. this._attachImageProcessingConfiguration(value);
  100146. // Ensure the effect will be rebuilt.
  100147. this._markAllSubMeshesAsTexturesDirty();
  100148. },
  100149. enumerable: true,
  100150. configurable: true
  100151. });
  100152. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  100153. /**
  100154. * Gets wether the color curves effect is enabled.
  100155. */
  100156. get: function () {
  100157. return this.imageProcessingConfiguration.colorCurvesEnabled;
  100158. },
  100159. /**
  100160. * Sets wether the color curves effect is enabled.
  100161. */
  100162. set: function (value) {
  100163. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  100164. },
  100165. enumerable: true,
  100166. configurable: true
  100167. });
  100168. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  100169. /**
  100170. * Gets wether the color grading effect is enabled.
  100171. */
  100172. get: function () {
  100173. return this.imageProcessingConfiguration.colorGradingEnabled;
  100174. },
  100175. /**
  100176. * Gets wether the color grading effect is enabled.
  100177. */
  100178. set: function (value) {
  100179. this.imageProcessingConfiguration.colorGradingEnabled = value;
  100180. },
  100181. enumerable: true,
  100182. configurable: true
  100183. });
  100184. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  100185. /**
  100186. * Gets wether tonemapping is enabled or not.
  100187. */
  100188. get: function () {
  100189. return this._imageProcessingConfiguration.toneMappingEnabled;
  100190. },
  100191. /**
  100192. * Sets wether tonemapping is enabled or not
  100193. */
  100194. set: function (value) {
  100195. this._imageProcessingConfiguration.toneMappingEnabled = value;
  100196. },
  100197. enumerable: true,
  100198. configurable: true
  100199. });
  100200. ;
  100201. ;
  100202. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  100203. /**
  100204. * The camera exposure used on this material.
  100205. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  100206. * This corresponds to a photographic exposure.
  100207. */
  100208. get: function () {
  100209. return this._imageProcessingConfiguration.exposure;
  100210. },
  100211. /**
  100212. * The camera exposure used on this material.
  100213. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  100214. * This corresponds to a photographic exposure.
  100215. */
  100216. set: function (value) {
  100217. this._imageProcessingConfiguration.exposure = value;
  100218. },
  100219. enumerable: true,
  100220. configurable: true
  100221. });
  100222. ;
  100223. ;
  100224. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  100225. /**
  100226. * Gets The camera contrast used on this material.
  100227. */
  100228. get: function () {
  100229. return this._imageProcessingConfiguration.contrast;
  100230. },
  100231. /**
  100232. * Sets The camera contrast used on this material.
  100233. */
  100234. set: function (value) {
  100235. this._imageProcessingConfiguration.contrast = value;
  100236. },
  100237. enumerable: true,
  100238. configurable: true
  100239. });
  100240. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  100241. /**
  100242. * Gets the Color Grading 2D Lookup Texture.
  100243. */
  100244. get: function () {
  100245. return this._imageProcessingConfiguration.colorGradingTexture;
  100246. },
  100247. /**
  100248. * Sets the Color Grading 2D Lookup Texture.
  100249. */
  100250. set: function (value) {
  100251. this.imageProcessingConfiguration.colorGradingTexture = value;
  100252. },
  100253. enumerable: true,
  100254. configurable: true
  100255. });
  100256. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  100257. /**
  100258. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  100259. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  100260. * 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;
  100261. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  100262. */
  100263. get: function () {
  100264. return this.imageProcessingConfiguration.colorCurves;
  100265. },
  100266. /**
  100267. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  100268. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  100269. * 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;
  100270. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  100271. */
  100272. set: function (value) {
  100273. this.imageProcessingConfiguration.colorCurves = value;
  100274. },
  100275. enumerable: true,
  100276. configurable: true
  100277. });
  100278. /**
  100279. * The entire material has been created in order to prevent overdraw.
  100280. * @returns false
  100281. */
  100282. BackgroundMaterial.prototype.needAlphaTesting = function () {
  100283. return true;
  100284. };
  100285. /**
  100286. * The entire material has been created in order to prevent overdraw.
  100287. * @returns true if blending is enable
  100288. */
  100289. BackgroundMaterial.prototype.needAlphaBlending = function () {
  100290. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  100291. };
  100292. /**
  100293. * Checks wether the material is ready to be rendered for a given mesh.
  100294. * @param mesh The mesh to render
  100295. * @param subMesh The submesh to check against
  100296. * @param useInstances Specify wether or not the material is used with instances
  100297. * @returns true if all the dependencies are ready (Textures, Effects...)
  100298. */
  100299. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  100300. var _this = this;
  100301. if (useInstances === void 0) { useInstances = false; }
  100302. if (subMesh.effect && this.isFrozen) {
  100303. if (this._wasPreviouslyReady) {
  100304. return true;
  100305. }
  100306. }
  100307. if (!subMesh._materialDefines) {
  100308. subMesh._materialDefines = new BackgroundMaterialDefines();
  100309. }
  100310. var scene = this.getScene();
  100311. var defines = subMesh._materialDefines;
  100312. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  100313. if (defines._renderId === scene.getRenderId()) {
  100314. return true;
  100315. }
  100316. }
  100317. var engine = scene.getEngine();
  100318. // Lights
  100319. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  100320. defines._needNormals = true;
  100321. // Textures
  100322. if (defines._areTexturesDirty) {
  100323. defines._needUVs = false;
  100324. if (scene.texturesEnabled) {
  100325. if (scene.getEngine().getCaps().textureLOD) {
  100326. defines.TEXTURELODSUPPORT = true;
  100327. }
  100328. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  100329. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  100330. return false;
  100331. }
  100332. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  100333. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  100334. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  100335. defines.OPACITYFRESNEL = this._opacityFresnel;
  100336. }
  100337. else {
  100338. defines.DIFFUSE = false;
  100339. defines.DIFFUSEHASALPHA = false;
  100340. defines.GAMMADIFFUSE = false;
  100341. defines.OPACITYFRESNEL = false;
  100342. }
  100343. var reflectionTexture = this._reflectionTexture;
  100344. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  100345. if (!reflectionTexture.isReadyOrNotBlocking()) {
  100346. return false;
  100347. }
  100348. defines.REFLECTION = true;
  100349. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  100350. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  100351. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  100352. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  100353. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  100354. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  100355. defines.REFLECTIONBGR = this.switchToBGR;
  100356. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  100357. defines.INVERTCUBICMAP = true;
  100358. }
  100359. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  100360. switch (reflectionTexture.coordinatesMode) {
  100361. case BABYLON.Texture.EXPLICIT_MODE:
  100362. defines.REFLECTIONMAP_EXPLICIT = true;
  100363. break;
  100364. case BABYLON.Texture.PLANAR_MODE:
  100365. defines.REFLECTIONMAP_PLANAR = true;
  100366. break;
  100367. case BABYLON.Texture.PROJECTION_MODE:
  100368. defines.REFLECTIONMAP_PROJECTION = true;
  100369. break;
  100370. case BABYLON.Texture.SKYBOX_MODE:
  100371. defines.REFLECTIONMAP_SKYBOX = true;
  100372. break;
  100373. case BABYLON.Texture.SPHERICAL_MODE:
  100374. defines.REFLECTIONMAP_SPHERICAL = true;
  100375. break;
  100376. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  100377. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  100378. break;
  100379. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  100380. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  100381. break;
  100382. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  100383. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  100384. break;
  100385. case BABYLON.Texture.CUBIC_MODE:
  100386. case BABYLON.Texture.INVCUBIC_MODE:
  100387. default:
  100388. defines.REFLECTIONMAP_CUBIC = true;
  100389. break;
  100390. }
  100391. if (this.reflectionFresnel) {
  100392. defines.REFLECTIONFRESNEL = true;
  100393. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  100394. this._reflectionControls.x = this.reflectionAmount;
  100395. this._reflectionControls.y = this.reflectionReflectance0;
  100396. this._reflectionControls.z = this.reflectionReflectance90;
  100397. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  100398. }
  100399. else {
  100400. defines.REFLECTIONFRESNEL = false;
  100401. defines.REFLECTIONFALLOFF = false;
  100402. }
  100403. }
  100404. else {
  100405. defines.REFLECTION = false;
  100406. defines.REFLECTIONFRESNEL = false;
  100407. defines.REFLECTIONFALLOFF = false;
  100408. defines.REFLECTIONBLUR = false;
  100409. defines.REFLECTIONMAP_3D = false;
  100410. defines.REFLECTIONMAP_SPHERICAL = false;
  100411. defines.REFLECTIONMAP_PLANAR = false;
  100412. defines.REFLECTIONMAP_CUBIC = false;
  100413. defines.REFLECTIONMAP_PROJECTION = false;
  100414. defines.REFLECTIONMAP_SKYBOX = false;
  100415. defines.REFLECTIONMAP_EXPLICIT = false;
  100416. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  100417. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  100418. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  100419. defines.INVERTCUBICMAP = false;
  100420. defines.REFLECTIONMAP_OPPOSITEZ = false;
  100421. defines.LODINREFLECTIONALPHA = false;
  100422. defines.GAMMAREFLECTION = false;
  100423. defines.RGBDREFLECTION = false;
  100424. }
  100425. }
  100426. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  100427. defines.USERGBCOLOR = this._useRGBColor;
  100428. defines.NOISE = this._enableNoise;
  100429. }
  100430. if (defines._areLightsDirty) {
  100431. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  100432. }
  100433. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  100434. if (!this._imageProcessingConfiguration.isReady()) {
  100435. return false;
  100436. }
  100437. this._imageProcessingConfiguration.prepareDefines(defines);
  100438. }
  100439. // Misc.
  100440. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  100441. // Values that need to be evaluated on every frame
  100442. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  100443. // Attribs
  100444. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  100445. if (mesh) {
  100446. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  100447. mesh.createNormals(true);
  100448. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  100449. }
  100450. }
  100451. }
  100452. // Get correct effect
  100453. if (defines.isDirty) {
  100454. defines.markAsProcessed();
  100455. scene.resetCachedMaterial();
  100456. // Fallbacks
  100457. var fallbacks = new BABYLON.EffectFallbacks();
  100458. if (defines.FOG) {
  100459. fallbacks.addFallback(0, "FOG");
  100460. }
  100461. if (defines.POINTSIZE) {
  100462. fallbacks.addFallback(1, "POINTSIZE");
  100463. }
  100464. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  100465. if (defines.NUM_BONE_INFLUENCERS > 0) {
  100466. fallbacks.addCPUSkinningFallback(0, mesh);
  100467. }
  100468. //Attributes
  100469. var attribs = [BABYLON.VertexBuffer.PositionKind];
  100470. if (defines.NORMAL) {
  100471. attribs.push(BABYLON.VertexBuffer.NormalKind);
  100472. }
  100473. if (defines.UV1) {
  100474. attribs.push(BABYLON.VertexBuffer.UVKind);
  100475. }
  100476. if (defines.UV2) {
  100477. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  100478. }
  100479. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  100480. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  100481. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  100482. "vFogInfos", "vFogColor", "pointSize",
  100483. "vClipPlane", "mBones",
  100484. "vPrimaryColor", "vPrimaryColorShadow",
  100485. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  100486. "shadowLevel", "alpha",
  100487. "vBackgroundCenter", "vReflectionControl",
  100488. "vDiffuseInfos", "diffuseMatrix",
  100489. ];
  100490. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  100491. var uniformBuffers = ["Material", "Scene"];
  100492. if (BABYLON.ImageProcessingConfiguration) {
  100493. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  100494. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  100495. }
  100496. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  100497. uniformsNames: uniforms,
  100498. uniformBuffersNames: uniformBuffers,
  100499. samplers: samplers,
  100500. defines: defines,
  100501. maxSimultaneousLights: this._maxSimultaneousLights
  100502. });
  100503. var onCompiled = function (effect) {
  100504. if (_this.onCompiled) {
  100505. _this.onCompiled(effect);
  100506. }
  100507. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  100508. };
  100509. var join = defines.toString();
  100510. subMesh.setEffect(scene.getEngine().createEffect("background", {
  100511. attributes: attribs,
  100512. uniformsNames: uniforms,
  100513. uniformBuffersNames: uniformBuffers,
  100514. samplers: samplers,
  100515. defines: join,
  100516. fallbacks: fallbacks,
  100517. onCompiled: onCompiled,
  100518. onError: this.onError,
  100519. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  100520. }, engine), defines);
  100521. this.buildUniformLayout();
  100522. }
  100523. if (!subMesh.effect || !subMesh.effect.isReady()) {
  100524. return false;
  100525. }
  100526. defines._renderId = scene.getRenderId();
  100527. this._wasPreviouslyReady = true;
  100528. return true;
  100529. };
  100530. /**
  100531. * Compute the primary color according to the chosen perceptual color.
  100532. */
  100533. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  100534. if (!this.__perceptualColor) {
  100535. return;
  100536. }
  100537. this._primaryColor.copyFrom(this.__perceptualColor);
  100538. // Revert gamma space.
  100539. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  100540. // Revert image processing configuration.
  100541. if (this._imageProcessingConfiguration) {
  100542. // Revert Exposure.
  100543. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  100544. }
  100545. this._computePrimaryColors();
  100546. };
  100547. /**
  100548. * Compute the highlights and shadow colors according to their chosen levels.
  100549. */
  100550. BackgroundMaterial.prototype._computePrimaryColors = function () {
  100551. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  100552. return;
  100553. }
  100554. // Find the highlight color based on the configuration.
  100555. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  100556. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  100557. // Find the shadow color based on the configuration.
  100558. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  100559. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  100560. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  100561. };
  100562. /**
  100563. * Build the uniform buffer used in the material.
  100564. */
  100565. BackgroundMaterial.prototype.buildUniformLayout = function () {
  100566. // Order is important !
  100567. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  100568. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  100569. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  100570. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  100571. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  100572. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  100573. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  100574. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  100575. this._uniformBuffer.addUniform("pointSize", 1);
  100576. this._uniformBuffer.addUniform("shadowLevel", 1);
  100577. this._uniformBuffer.addUniform("alpha", 1);
  100578. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  100579. this._uniformBuffer.addUniform("vReflectionControl", 4);
  100580. this._uniformBuffer.create();
  100581. };
  100582. /**
  100583. * Unbind the material.
  100584. */
  100585. BackgroundMaterial.prototype.unbind = function () {
  100586. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  100587. this._uniformBuffer.setTexture("diffuseSampler", null);
  100588. }
  100589. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  100590. this._uniformBuffer.setTexture("reflectionSampler", null);
  100591. }
  100592. _super.prototype.unbind.call(this);
  100593. };
  100594. /**
  100595. * Bind only the world matrix to the material.
  100596. * @param world The world matrix to bind.
  100597. */
  100598. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  100599. this._activeEffect.setMatrix("world", world);
  100600. };
  100601. /**
  100602. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  100603. * @param world The world matrix to bind.
  100604. * @param subMesh The submesh to bind for.
  100605. */
  100606. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  100607. var scene = this.getScene();
  100608. var defines = subMesh._materialDefines;
  100609. if (!defines) {
  100610. return;
  100611. }
  100612. var effect = subMesh.effect;
  100613. if (!effect) {
  100614. return;
  100615. }
  100616. this._activeEffect = effect;
  100617. // Matrices
  100618. this.bindOnlyWorldMatrix(world);
  100619. // Bones
  100620. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  100621. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  100622. if (mustRebind) {
  100623. this._uniformBuffer.bindToEffect(effect, "Material");
  100624. this.bindViewProjection(effect);
  100625. var reflectionTexture = this._reflectionTexture;
  100626. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  100627. // Texture uniforms
  100628. if (scene.texturesEnabled) {
  100629. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  100630. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  100631. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  100632. }
  100633. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  100634. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  100635. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  100636. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  100637. }
  100638. }
  100639. if (this.shadowLevel > 0) {
  100640. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  100641. }
  100642. this._uniformBuffer.updateFloat("alpha", this.alpha);
  100643. // Point size
  100644. if (this.pointsCloud) {
  100645. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  100646. }
  100647. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  100648. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  100649. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  100650. }
  100651. else {
  100652. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  100653. }
  100654. }
  100655. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  100656. // Textures
  100657. if (scene.texturesEnabled) {
  100658. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  100659. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  100660. }
  100661. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  100662. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  100663. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  100664. }
  100665. else if (!defines.REFLECTIONBLUR) {
  100666. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  100667. }
  100668. else {
  100669. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  100670. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  100671. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  100672. }
  100673. if (defines.REFLECTIONFRESNEL) {
  100674. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  100675. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  100676. }
  100677. }
  100678. }
  100679. // Clip plane
  100680. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  100681. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  100682. }
  100683. if (mustRebind || !this.isFrozen) {
  100684. if (scene.lightsEnabled) {
  100685. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  100686. }
  100687. // View
  100688. this.bindView(effect);
  100689. // Fog
  100690. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  100691. // image processing
  100692. if (this._imageProcessingConfiguration) {
  100693. this._imageProcessingConfiguration.bind(this._activeEffect);
  100694. }
  100695. }
  100696. this._uniformBuffer.update();
  100697. this._afterBind(mesh, this._activeEffect);
  100698. };
  100699. /**
  100700. * Dispose the material.
  100701. * @param forceDisposeEffect Force disposal of the associated effect.
  100702. * @param forceDisposeTextures Force disposal of the associated textures.
  100703. */
  100704. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  100705. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  100706. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  100707. if (forceDisposeTextures) {
  100708. if (this.diffuseTexture) {
  100709. this.diffuseTexture.dispose();
  100710. }
  100711. if (this.reflectionTexture) {
  100712. this.reflectionTexture.dispose();
  100713. }
  100714. }
  100715. this._renderTargets.dispose();
  100716. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  100717. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  100718. }
  100719. _super.prototype.dispose.call(this, forceDisposeEffect);
  100720. };
  100721. /**
  100722. * Clones the material.
  100723. * @param name The cloned name.
  100724. * @returns The cloned material.
  100725. */
  100726. BackgroundMaterial.prototype.clone = function (name) {
  100727. var _this = this;
  100728. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  100729. };
  100730. /**
  100731. * Serializes the current material to its JSON representation.
  100732. * @returns The JSON representation.
  100733. */
  100734. BackgroundMaterial.prototype.serialize = function () {
  100735. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  100736. serializationObject.customType = "BABYLON.BackgroundMaterial";
  100737. return serializationObject;
  100738. };
  100739. /**
  100740. * Gets the class name of the material
  100741. * @returns "BackgroundMaterial"
  100742. */
  100743. BackgroundMaterial.prototype.getClassName = function () {
  100744. return "BackgroundMaterial";
  100745. };
  100746. /**
  100747. * Parse a JSON input to create back a background material.
  100748. * @param source The JSON data to parse
  100749. * @param scene The scene to create the parsed material in
  100750. * @param rootUrl The root url of the assets the material depends upon
  100751. * @returns the instantiated BackgroundMaterial.
  100752. */
  100753. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  100754. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  100755. };
  100756. /**
  100757. * Standard reflectance value at parallel view angle.
  100758. */
  100759. BackgroundMaterial.StandardReflectance0 = 0.05;
  100760. /**
  100761. * Standard reflectance value at grazing angle.
  100762. */
  100763. BackgroundMaterial.StandardReflectance90 = 0.5;
  100764. __decorate([
  100765. BABYLON.serializeAsColor3()
  100766. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  100767. __decorate([
  100768. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  100769. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  100770. __decorate([
  100771. BABYLON.serializeAsColor3()
  100772. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  100773. __decorate([
  100774. BABYLON.serialize()
  100775. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  100776. __decorate([
  100777. BABYLON.serialize()
  100778. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  100779. __decorate([
  100780. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  100781. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  100782. __decorate([
  100783. BABYLON.serializeAsTexture()
  100784. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  100785. __decorate([
  100786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100787. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  100788. __decorate([
  100789. BABYLON.serialize()
  100790. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  100791. __decorate([
  100792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100793. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  100794. __decorate([
  100795. BABYLON.serializeAsTexture()
  100796. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  100797. __decorate([
  100798. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100799. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  100800. __decorate([
  100801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100802. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  100803. __decorate([
  100804. BABYLON.serialize()
  100805. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  100806. __decorate([
  100807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100808. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  100809. __decorate([
  100810. BABYLON.serializeAsVector3()
  100811. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  100812. __decorate([
  100813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100814. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  100815. __decorate([
  100816. BABYLON.serialize()
  100817. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  100818. __decorate([
  100819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100820. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  100821. __decorate([
  100822. BABYLON.serialize()
  100823. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  100824. __decorate([
  100825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100826. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  100827. __decorate([
  100828. BABYLON.serialize()
  100829. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  100830. __decorate([
  100831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100832. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  100833. __decorate([
  100834. BABYLON.serialize()
  100835. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  100836. __decorate([
  100837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100838. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  100839. __decorate([
  100840. BABYLON.serialize()
  100841. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  100842. __decorate([
  100843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100844. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  100845. __decorate([
  100846. BABYLON.serialize()
  100847. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  100848. __decorate([
  100849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100850. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  100851. __decorate([
  100852. BABYLON.serialize()
  100853. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  100854. __decorate([
  100855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100856. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  100857. __decorate([
  100858. BABYLON.serialize()
  100859. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  100860. __decorate([
  100861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100862. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  100863. __decorate([
  100864. BABYLON.serialize()
  100865. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  100866. __decorate([
  100867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100868. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  100869. __decorate([
  100870. BABYLON.serializeAsImageProcessingConfiguration()
  100871. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  100872. return BackgroundMaterial;
  100873. }(BABYLON.PushMaterial));
  100874. BABYLON.BackgroundMaterial = BackgroundMaterial;
  100875. })(BABYLON || (BABYLON = {}));
  100876. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  100877. var __assign = (this && this.__assign) || Object.assign || function(t) {
  100878. for (var s, i = 1, n = arguments.length; i < n; i++) {
  100879. s = arguments[i];
  100880. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  100881. t[p] = s[p];
  100882. }
  100883. return t;
  100884. };
  100885. var BABYLON;
  100886. (function (BABYLON) {
  100887. /**
  100888. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  100889. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  100890. * It also helps with the default setup of your imageProcessing configuration.
  100891. */
  100892. var EnvironmentHelper = /** @class */ (function () {
  100893. /**
  100894. * constructor
  100895. * @param options
  100896. * @param scene The scene to add the material to
  100897. */
  100898. function EnvironmentHelper(options, scene) {
  100899. var _this = this;
  100900. this._errorHandler = function (message, exception) {
  100901. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  100902. };
  100903. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  100904. this._scene = scene;
  100905. this.onErrorObservable = new BABYLON.Observable();
  100906. this._setupBackground();
  100907. this._setupImageProcessing();
  100908. }
  100909. /**
  100910. * Creates the default options for the helper.
  100911. */
  100912. EnvironmentHelper._getDefaultOptions = function () {
  100913. return {
  100914. createGround: true,
  100915. groundSize: 15,
  100916. groundTexture: this._groundTextureCDNUrl,
  100917. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  100918. groundOpacity: 0.9,
  100919. enableGroundShadow: true,
  100920. groundShadowLevel: 0.5,
  100921. enableGroundMirror: false,
  100922. groundMirrorSizeRatio: 0.3,
  100923. groundMirrorBlurKernel: 64,
  100924. groundMirrorAmount: 1,
  100925. groundMirrorFresnelWeight: 1,
  100926. groundMirrorFallOffDistance: 0,
  100927. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  100928. groundYBias: 0.00001,
  100929. createSkybox: true,
  100930. skyboxSize: 20,
  100931. skyboxTexture: this._skyboxTextureCDNUrl,
  100932. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  100933. backgroundYRotation: 0,
  100934. sizeAuto: true,
  100935. rootPosition: BABYLON.Vector3.Zero(),
  100936. setupImageProcessing: true,
  100937. environmentTexture: this._environmentTextureCDNUrl,
  100938. cameraExposure: 0.8,
  100939. cameraContrast: 1.2,
  100940. toneMappingEnabled: true,
  100941. };
  100942. };
  100943. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  100944. /**
  100945. * Gets the root mesh created by the helper.
  100946. */
  100947. get: function () {
  100948. return this._rootMesh;
  100949. },
  100950. enumerable: true,
  100951. configurable: true
  100952. });
  100953. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  100954. /**
  100955. * Gets the skybox created by the helper.
  100956. */
  100957. get: function () {
  100958. return this._skybox;
  100959. },
  100960. enumerable: true,
  100961. configurable: true
  100962. });
  100963. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  100964. /**
  100965. * Gets the skybox texture created by the helper.
  100966. */
  100967. get: function () {
  100968. return this._skyboxTexture;
  100969. },
  100970. enumerable: true,
  100971. configurable: true
  100972. });
  100973. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  100974. /**
  100975. * Gets the skybox material created by the helper.
  100976. */
  100977. get: function () {
  100978. return this._skyboxMaterial;
  100979. },
  100980. enumerable: true,
  100981. configurable: true
  100982. });
  100983. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  100984. /**
  100985. * Gets the ground mesh created by the helper.
  100986. */
  100987. get: function () {
  100988. return this._ground;
  100989. },
  100990. enumerable: true,
  100991. configurable: true
  100992. });
  100993. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  100994. /**
  100995. * Gets the ground texture created by the helper.
  100996. */
  100997. get: function () {
  100998. return this._groundTexture;
  100999. },
  101000. enumerable: true,
  101001. configurable: true
  101002. });
  101003. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  101004. /**
  101005. * Gets the ground mirror created by the helper.
  101006. */
  101007. get: function () {
  101008. return this._groundMirror;
  101009. },
  101010. enumerable: true,
  101011. configurable: true
  101012. });
  101013. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  101014. /**
  101015. * Gets the ground mirror render list to helps pushing the meshes
  101016. * you wish in the ground reflection.
  101017. */
  101018. get: function () {
  101019. if (this._groundMirror) {
  101020. return this._groundMirror.renderList;
  101021. }
  101022. return null;
  101023. },
  101024. enumerable: true,
  101025. configurable: true
  101026. });
  101027. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  101028. /**
  101029. * Gets the ground material created by the helper.
  101030. */
  101031. get: function () {
  101032. return this._groundMaterial;
  101033. },
  101034. enumerable: true,
  101035. configurable: true
  101036. });
  101037. /**
  101038. * Updates the background according to the new options
  101039. * @param options
  101040. */
  101041. EnvironmentHelper.prototype.updateOptions = function (options) {
  101042. var newOptions = __assign({}, this._options, options);
  101043. if (this._ground && !newOptions.createGround) {
  101044. this._ground.dispose();
  101045. this._ground = null;
  101046. }
  101047. if (this._groundMaterial && !newOptions.createGround) {
  101048. this._groundMaterial.dispose();
  101049. this._groundMaterial = null;
  101050. }
  101051. if (this._groundTexture) {
  101052. if (this._options.groundTexture != newOptions.groundTexture) {
  101053. this._groundTexture.dispose();
  101054. this._groundTexture = null;
  101055. }
  101056. }
  101057. if (this._skybox && !newOptions.createSkybox) {
  101058. this._skybox.dispose();
  101059. this._skybox = null;
  101060. }
  101061. if (this._skyboxMaterial && !newOptions.createSkybox) {
  101062. this._skyboxMaterial.dispose();
  101063. this._skyboxMaterial = null;
  101064. }
  101065. if (this._skyboxTexture) {
  101066. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  101067. this._skyboxTexture.dispose();
  101068. this._skyboxTexture = null;
  101069. }
  101070. }
  101071. if (this._groundMirror && !newOptions.enableGroundMirror) {
  101072. this._groundMirror.dispose();
  101073. this._groundMirror = null;
  101074. }
  101075. if (this._scene.environmentTexture) {
  101076. if (this._options.environmentTexture != newOptions.environmentTexture) {
  101077. this._scene.environmentTexture.dispose();
  101078. }
  101079. }
  101080. this._options = newOptions;
  101081. this._setupBackground();
  101082. this._setupImageProcessing();
  101083. };
  101084. /**
  101085. * Sets the primary color of all the available elements.
  101086. * @param color the main color to affect to the ground and the background
  101087. */
  101088. EnvironmentHelper.prototype.setMainColor = function (color) {
  101089. if (this.groundMaterial) {
  101090. this.groundMaterial.primaryColor = color;
  101091. }
  101092. if (this.skyboxMaterial) {
  101093. this.skyboxMaterial.primaryColor = color;
  101094. }
  101095. if (this.groundMirror) {
  101096. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  101097. }
  101098. };
  101099. /**
  101100. * Setup the image processing according to the specified options.
  101101. */
  101102. EnvironmentHelper.prototype._setupImageProcessing = function () {
  101103. if (this._options.setupImageProcessing) {
  101104. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  101105. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  101106. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  101107. this._setupEnvironmentTexture();
  101108. }
  101109. };
  101110. /**
  101111. * Setup the environment texture according to the specified options.
  101112. */
  101113. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  101114. if (this._scene.environmentTexture) {
  101115. return;
  101116. }
  101117. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  101118. this._scene.environmentTexture = this._options.environmentTexture;
  101119. return;
  101120. }
  101121. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  101122. this._scene.environmentTexture = environmentTexture;
  101123. };
  101124. /**
  101125. * Setup the background according to the specified options.
  101126. */
  101127. EnvironmentHelper.prototype._setupBackground = function () {
  101128. if (!this._rootMesh) {
  101129. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  101130. }
  101131. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  101132. var sceneSize = this._getSceneSize();
  101133. if (this._options.createGround) {
  101134. this._setupGround(sceneSize);
  101135. this._setupGroundMaterial();
  101136. this._setupGroundDiffuseTexture();
  101137. if (this._options.enableGroundMirror) {
  101138. this._setupGroundMirrorTexture(sceneSize);
  101139. }
  101140. this._setupMirrorInGroundMaterial();
  101141. }
  101142. if (this._options.createSkybox) {
  101143. this._setupSkybox(sceneSize);
  101144. this._setupSkyboxMaterial();
  101145. this._setupSkyboxReflectionTexture();
  101146. }
  101147. this._rootMesh.position.x = sceneSize.rootPosition.x;
  101148. this._rootMesh.position.z = sceneSize.rootPosition.z;
  101149. this._rootMesh.position.y = sceneSize.rootPosition.y;
  101150. };
  101151. /**
  101152. * Get the scene sizes according to the setup.
  101153. */
  101154. EnvironmentHelper.prototype._getSceneSize = function () {
  101155. var _this = this;
  101156. var groundSize = this._options.groundSize;
  101157. var skyboxSize = this._options.skyboxSize;
  101158. var rootPosition = this._options.rootPosition;
  101159. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  101160. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  101161. }
  101162. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  101163. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  101164. });
  101165. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  101166. if (this._options.sizeAuto) {
  101167. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  101168. this._scene.activeCamera.upperRadiusLimit) {
  101169. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  101170. skyboxSize = groundSize;
  101171. }
  101172. var sceneDiagonalLenght = sceneDiagonal.length();
  101173. if (sceneDiagonalLenght > groundSize) {
  101174. groundSize = sceneDiagonalLenght * 2;
  101175. skyboxSize = groundSize;
  101176. }
  101177. // 10 % bigger.
  101178. groundSize *= 1.1;
  101179. skyboxSize *= 1.5;
  101180. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  101181. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  101182. }
  101183. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  101184. };
  101185. /**
  101186. * Setup the ground according to the specified options.
  101187. */
  101188. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  101189. var _this = this;
  101190. if (!this._ground || this._ground.isDisposed()) {
  101191. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  101192. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  101193. this._ground.parent = this._rootMesh;
  101194. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  101195. }
  101196. this._ground.receiveShadows = this._options.enableGroundShadow;
  101197. };
  101198. /**
  101199. * Setup the ground material according to the specified options.
  101200. */
  101201. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  101202. if (!this._groundMaterial) {
  101203. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  101204. }
  101205. this._groundMaterial.alpha = this._options.groundOpacity;
  101206. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  101207. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  101208. this._groundMaterial.primaryColor = this._options.groundColor;
  101209. this._groundMaterial.useRGBColor = false;
  101210. this._groundMaterial.enableNoise = true;
  101211. if (this._ground) {
  101212. this._ground.material = this._groundMaterial;
  101213. }
  101214. };
  101215. /**
  101216. * Setup the ground diffuse texture according to the specified options.
  101217. */
  101218. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  101219. if (!this._groundMaterial) {
  101220. return;
  101221. }
  101222. if (this._groundTexture) {
  101223. return;
  101224. }
  101225. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  101226. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  101227. return;
  101228. }
  101229. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  101230. diffuseTexture.gammaSpace = false;
  101231. diffuseTexture.hasAlpha = true;
  101232. this._groundMaterial.diffuseTexture = diffuseTexture;
  101233. };
  101234. /**
  101235. * Setup the ground mirror texture according to the specified options.
  101236. */
  101237. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  101238. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101239. if (!this._groundMirror) {
  101240. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  101241. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  101242. this._groundMirror.anisotropicFilteringLevel = 1;
  101243. this._groundMirror.wrapU = wrapping;
  101244. this._groundMirror.wrapV = wrapping;
  101245. this._groundMirror.gammaSpace = false;
  101246. if (this._groundMirror.renderList) {
  101247. for (var i = 0; i < this._scene.meshes.length; i++) {
  101248. var mesh = this._scene.meshes[i];
  101249. if (mesh !== this._ground &&
  101250. mesh !== this._skybox &&
  101251. mesh !== this._rootMesh) {
  101252. this._groundMirror.renderList.push(mesh);
  101253. }
  101254. }
  101255. }
  101256. }
  101257. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  101258. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  101259. };
  101260. /**
  101261. * Setup the ground to receive the mirror texture.
  101262. */
  101263. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  101264. if (this._groundMaterial) {
  101265. this._groundMaterial.reflectionTexture = this._groundMirror;
  101266. this._groundMaterial.reflectionFresnel = true;
  101267. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  101268. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  101269. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  101270. }
  101271. };
  101272. /**
  101273. * Setup the skybox according to the specified options.
  101274. */
  101275. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  101276. var _this = this;
  101277. if (!this._skybox || this._skybox.isDisposed()) {
  101278. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  101279. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  101280. }
  101281. this._skybox.parent = this._rootMesh;
  101282. };
  101283. /**
  101284. * Setup the skybox material according to the specified options.
  101285. */
  101286. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  101287. if (!this._skybox) {
  101288. return;
  101289. }
  101290. if (!this._skyboxMaterial) {
  101291. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  101292. }
  101293. this._skyboxMaterial.useRGBColor = false;
  101294. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  101295. this._skyboxMaterial.enableNoise = true;
  101296. this._skybox.material = this._skyboxMaterial;
  101297. };
  101298. /**
  101299. * Setup the skybox reflection texture according to the specified options.
  101300. */
  101301. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  101302. if (!this._skyboxMaterial) {
  101303. return;
  101304. }
  101305. if (this._skyboxTexture) {
  101306. return;
  101307. }
  101308. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  101309. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  101310. return;
  101311. }
  101312. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  101313. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  101314. this._skyboxTexture.gammaSpace = false;
  101315. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  101316. };
  101317. /**
  101318. * Dispose all the elements created by the Helper.
  101319. */
  101320. EnvironmentHelper.prototype.dispose = function () {
  101321. if (this._groundMaterial) {
  101322. this._groundMaterial.dispose(true, true);
  101323. }
  101324. if (this._skyboxMaterial) {
  101325. this._skyboxMaterial.dispose(true, true);
  101326. }
  101327. this._rootMesh.dispose(false);
  101328. };
  101329. /**
  101330. * Default ground texture URL.
  101331. */
  101332. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  101333. /**
  101334. * Default skybox texture URL.
  101335. */
  101336. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  101337. /**
  101338. * Default environment texture URL.
  101339. */
  101340. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  101341. return EnvironmentHelper;
  101342. }());
  101343. BABYLON.EnvironmentHelper = EnvironmentHelper;
  101344. })(BABYLON || (BABYLON = {}));
  101345. //# sourceMappingURL=babylon.environmentHelper.js.map
  101346. var BABYLON;
  101347. (function (BABYLON) {
  101348. /**
  101349. * This class is made for on one-liner static method to help creating particle systems.
  101350. */
  101351. var ParticleHelper = /** @class */ (function () {
  101352. function ParticleHelper() {
  101353. }
  101354. /**
  101355. * This is the main static method (one-liner) of this helper to create different particle systems.
  101356. * @param type This string represents the type to the particle system to create
  101357. * @param emitter The object where the particle system will start to emit from.
  101358. * @param scene The scene where the particle system should live.
  101359. * @param gpu If the system will use gpu.
  101360. * @returns the ParticleSystem created.
  101361. */
  101362. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  101363. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  101364. if (gpu === void 0) { gpu = false; }
  101365. return new Promise(function (resolve, reject) {
  101366. if (!scene) {
  101367. scene = BABYLON.Engine.LastCreatedScene;
  101368. ;
  101369. }
  101370. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  101371. return reject("Particle system with GPU is not supported.");
  101372. }
  101373. BABYLON.Tools.LoadFile(ParticleHelper._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  101374. var newData = JSON.parse(data.toString());
  101375. return resolve(ParticleHelper.CreateSystem(newData, scene, emitter));
  101376. }, undefined, undefined, undefined, function (req, exception) {
  101377. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  101378. });
  101379. });
  101380. };
  101381. /**
  101382. * Static function used to create a new particle system from a IParticleSystemData
  101383. * @param data defines the source data
  101384. * @param scene defines the hosting scene
  101385. * @param emitter defines the particle emitter
  101386. * @returns a new ParticleSystem based on referenced data
  101387. */
  101388. ParticleHelper.CreateSystem = function (data, scene, emitter) {
  101389. // Create a particle system
  101390. var system = new BABYLON.ParticleSystem(data.type, data.capacity, scene);
  101391. // Where the particles come from
  101392. system.emitter = emitter; // the starting object, the emitter
  101393. ParticleHelper.UpdateSystem(system, data, scene);
  101394. return system;
  101395. };
  101396. /**
  101397. * Static function used to update a particle system from a IParticleSystemData
  101398. * @param system defines the particle system to update
  101399. * @param data defines the source data
  101400. * @param scene defines the hosting scene
  101401. */
  101402. ParticleHelper.UpdateSystem = function (system, data, scene) {
  101403. // Texture of each particle
  101404. if (data.textureFile) {
  101405. system.particleTexture = new BABYLON.Texture(ParticleHelper._baseAssetsUrl + "/textures/" + data.textureFile, scene);
  101406. }
  101407. // Colors of all particles
  101408. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  101409. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  101410. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  101411. // Size of each particle (random between...
  101412. system.minSize = data.minSize;
  101413. system.maxSize = data.maxSize;
  101414. system.minScaleX = data.minScaleX;
  101415. system.maxScaleX = data.maxScaleX;
  101416. system.minScaleY = data.minScaleY;
  101417. system.maxScaleY = data.maxScaleY;
  101418. // Life time of each particle (random between...
  101419. system.minLifeTime = data.minLifeTime;
  101420. system.maxLifeTime = data.maxLifeTime;
  101421. // Emission rate
  101422. system.emitRate = data.emitRate;
  101423. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  101424. system.blendMode = data.blendMode;
  101425. // Set the gravity of all particles
  101426. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  101427. // Angular speed, in radians
  101428. system.minAngularSpeed = data.minAngularSpeed;
  101429. system.maxAngularSpeed = data.maxAngularSpeed;
  101430. // Speed
  101431. system.minEmitPower = data.minEmitPower;
  101432. system.maxEmitPower = data.maxEmitPower;
  101433. system.updateSpeed = data.updateSpeed;
  101434. switch (data.emitterType) {
  101435. case "box":
  101436. if (!data.direction1 || !data.direction2) {
  101437. throw new Error("Directions are missing in this particle system.");
  101438. }
  101439. if (!data.minEmitBox || !data.maxEmitBox) {
  101440. throw new Error("EmitBox is missing in this particle system.");
  101441. }
  101442. system.createBoxEmitter(new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z), new BABYLON.Vector3(data.minEmitBox.x, data.minEmitBox.y, data.minEmitBox.z), new BABYLON.Vector3(data.maxEmitBox.x, data.maxEmitBox.y, data.maxEmitBox.z));
  101443. break;
  101444. case "sphere":
  101445. system.createSphereEmitter(data.radius);
  101446. break;
  101447. case "directed_sphere":
  101448. if (!data.direction1 || !data.direction2) {
  101449. throw new Error("Directions are missing in this particle system.");
  101450. }
  101451. system.createDirectedSphereEmitter(data.radius, new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z));
  101452. break;
  101453. case "cone":
  101454. system.createConeEmitter(data.radius, data.angle);
  101455. break;
  101456. default:
  101457. break;
  101458. }
  101459. };
  101460. /**
  101461. * Static function used to export a particle system to a IParticleSystemData variable.
  101462. * Please note that texture file name is not exported and must be added manually
  101463. * @param system defines the particle system to export
  101464. */
  101465. ParticleHelper.ExportSystem = function (system) {
  101466. var outData = {};
  101467. // Colors of all particles
  101468. outData.color1 = { r: system.color1.r, g: system.color1.g, b: system.color1.b, a: system.color1.a };
  101469. outData.color2 = { r: system.color2.r, g: system.color2.g, b: system.color2.b, a: system.color2.a };
  101470. outData.colorDead = { r: system.colorDead.r, g: system.colorDead.g, b: system.colorDead.b, a: system.colorDead.a };
  101471. // Size of each particle (random between...
  101472. outData.minSize = system.minSize;
  101473. outData.maxSize = system.maxSize;
  101474. outData.minScaleX = system.minScaleX;
  101475. outData.maxScaleX = system.maxScaleX;
  101476. outData.minScaleY = system.minScaleY;
  101477. outData.maxScaleY = system.maxScaleY;
  101478. // Life time of each particle (random between...
  101479. outData.minLifeTime = system.minLifeTime;
  101480. outData.maxLifeTime = system.maxLifeTime;
  101481. // Emission rate
  101482. outData.emitRate = system.emitRate;
  101483. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  101484. outData.blendMode = system.blendMode;
  101485. // Set the gravity of all particles
  101486. outData.gravity = { x: system.gravity.x, y: system.gravity.y, z: system.gravity.z };
  101487. // Angular speed, in radians
  101488. outData.minAngularSpeed = system.minAngularSpeed;
  101489. outData.maxAngularSpeed = system.maxAngularSpeed;
  101490. // Speed
  101491. outData.minEmitPower = system.minEmitPower;
  101492. outData.maxEmitPower = system.maxEmitPower;
  101493. outData.updateSpeed = system.updateSpeed;
  101494. switch (system.particleEmitterType.getClassName()) {
  101495. case "BoxEmitter":
  101496. outData.emitterType = "box";
  101497. outData.direction1 = { x: system.direction1.x, y: system.direction1.y, z: system.direction1.z };
  101498. outData.direction2 = { x: system.direction2.x, y: system.direction2.y, z: system.direction2.z };
  101499. outData.minEmitBox = { x: system.minEmitBox.x, y: system.minEmitBox.y, z: system.minEmitBox.z };
  101500. outData.maxEmitBox = { x: system.maxEmitBox.x, y: system.maxEmitBox.y, z: system.maxEmitBox.z };
  101501. break;
  101502. case "SphereParticleEmitter":
  101503. outData.emitterType = "sphere";
  101504. outData.radius = system.particleEmitterType.radius;
  101505. break;
  101506. case "SphereDirectedParticleEmitter":
  101507. outData.emitterType = "directed_sphere";
  101508. var sphereDirectedParticleEmitter = system.particleEmitterType;
  101509. outData.radius = sphereDirectedParticleEmitter.radius;
  101510. outData.direction1 = { x: sphereDirectedParticleEmitter.direction1.x, y: sphereDirectedParticleEmitter.direction1.y, z: sphereDirectedParticleEmitter.direction1.z };
  101511. outData.direction2 = { x: sphereDirectedParticleEmitter.direction2.x, y: sphereDirectedParticleEmitter.direction2.y, z: sphereDirectedParticleEmitter.direction2.z };
  101512. break;
  101513. case "ConeEmitter":
  101514. outData.emitterType = "cone";
  101515. outData.radius = system.particleEmitterType.radius;
  101516. outData.angle = system.particleEmitterType.angle;
  101517. break;
  101518. default:
  101519. break;
  101520. }
  101521. return outData;
  101522. };
  101523. /**
  101524. * Base Assets URL.
  101525. */
  101526. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  101527. return ParticleHelper;
  101528. }());
  101529. BABYLON.ParticleHelper = ParticleHelper;
  101530. })(BABYLON || (BABYLON = {}));
  101531. //# sourceMappingURL=babylon.particleHelper.js.map
  101532. var BABYLON;
  101533. (function (BABYLON) {
  101534. /**
  101535. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  101536. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  101537. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  101538. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  101539. */
  101540. var VideoDome = /** @class */ (function (_super) {
  101541. __extends(VideoDome, _super);
  101542. /**
  101543. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  101544. * @param name Element's name, child elements will append suffixes for their own names.
  101545. * @param urlsOrVideo defines the url(s) or the video element to use
  101546. * @param options An object containing optional or exposed sub element properties
  101547. */
  101548. function VideoDome(name, urlsOrVideo, options, scene) {
  101549. var _this = _super.call(this, name, scene) || this;
  101550. _this._useDirectMapping = false;
  101551. // set defaults and manage values
  101552. name = name || "videoDome";
  101553. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  101554. options.clickToPlay = Boolean(options.clickToPlay);
  101555. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  101556. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  101557. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  101558. if (options.useDirectMapping === undefined) {
  101559. _this._useDirectMapping = true;
  101560. }
  101561. else {
  101562. _this._useDirectMapping = options.useDirectMapping;
  101563. }
  101564. // create
  101565. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  101566. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  101567. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  101568. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  101569. // configure material
  101570. material.useEquirectangularFOV = true;
  101571. material.fovMultiplier = 1.0;
  101572. material.opacityFresnel = false;
  101573. if (_this._useDirectMapping) {
  101574. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101575. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101576. material.diffuseTexture = texture;
  101577. }
  101578. else {
  101579. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  101580. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101581. material.reflectionTexture = texture;
  101582. }
  101583. // configure mesh
  101584. _this._mesh.material = material;
  101585. _this._mesh.parent = _this;
  101586. // optional configuration
  101587. if (options.clickToPlay) {
  101588. scene.onPointerUp = function () {
  101589. _this._videoTexture.video.play();
  101590. };
  101591. }
  101592. return _this;
  101593. }
  101594. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  101595. /**
  101596. * Gets the video texture being displayed on the sphere
  101597. */
  101598. get: function () {
  101599. return this._videoTexture;
  101600. },
  101601. enumerable: true,
  101602. configurable: true
  101603. });
  101604. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  101605. /**
  101606. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  101607. * Also see the options.resolution property.
  101608. */
  101609. get: function () {
  101610. return this._material.fovMultiplier;
  101611. },
  101612. set: function (value) {
  101613. this._material.fovMultiplier = value;
  101614. },
  101615. enumerable: true,
  101616. configurable: true
  101617. });
  101618. /**
  101619. * Releases resources associated with this node.
  101620. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  101621. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  101622. */
  101623. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  101624. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  101625. this._videoTexture.dispose();
  101626. this._mesh.dispose();
  101627. this._material.dispose();
  101628. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  101629. };
  101630. return VideoDome;
  101631. }(BABYLON.Node));
  101632. BABYLON.VideoDome = VideoDome;
  101633. })(BABYLON || (BABYLON = {}));
  101634. //# sourceMappingURL=babylon.videoDome.js.map
  101635. var BABYLON;
  101636. (function (BABYLON) {
  101637. /**
  101638. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  101639. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  101640. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  101641. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  101642. */
  101643. var PhotoDome = /** @class */ (function (_super) {
  101644. __extends(PhotoDome, _super);
  101645. /**
  101646. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  101647. * @param name Element's name, child elements will append suffixes for their own names.
  101648. * @param urlsOfPhoto define the url of the photo to display
  101649. * @param options An object containing optional or exposed sub element properties
  101650. */
  101651. function PhotoDome(name, urlOfPhoto, options, scene) {
  101652. var _this = _super.call(this, name, scene) || this;
  101653. _this._useDirectMapping = false;
  101654. // set defaults and manage values
  101655. name = name || "photoDome";
  101656. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  101657. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  101658. if (options.useDirectMapping === undefined) {
  101659. _this._useDirectMapping = true;
  101660. }
  101661. else {
  101662. _this._useDirectMapping = options.useDirectMapping;
  101663. }
  101664. // create
  101665. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  101666. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  101667. // configure material
  101668. material.opacityFresnel = false;
  101669. material.useEquirectangularFOV = true;
  101670. material.fovMultiplier = 1.0;
  101671. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  101672. // configure mesh
  101673. _this._mesh.material = material;
  101674. _this._mesh.parent = _this;
  101675. return _this;
  101676. }
  101677. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  101678. /**
  101679. * Gets or sets the texture being displayed on the sphere
  101680. */
  101681. get: function () {
  101682. return this._photoTexture;
  101683. },
  101684. set: function (value) {
  101685. if (this._photoTexture === value) {
  101686. return;
  101687. }
  101688. this._photoTexture = value;
  101689. if (this._useDirectMapping) {
  101690. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101691. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101692. this._material.diffuseTexture = this._photoTexture;
  101693. }
  101694. else {
  101695. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  101696. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101697. this._material.reflectionTexture = this._photoTexture;
  101698. }
  101699. },
  101700. enumerable: true,
  101701. configurable: true
  101702. });
  101703. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  101704. /**
  101705. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  101706. * Also see the options.resolution property.
  101707. */
  101708. get: function () {
  101709. return this._material.fovMultiplier;
  101710. },
  101711. set: function (value) {
  101712. this._material.fovMultiplier = value;
  101713. },
  101714. enumerable: true,
  101715. configurable: true
  101716. });
  101717. /**
  101718. * Releases resources associated with this node.
  101719. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  101720. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  101721. */
  101722. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  101723. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  101724. this._photoTexture.dispose();
  101725. this._mesh.dispose();
  101726. this._material.dispose();
  101727. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  101728. };
  101729. return PhotoDome;
  101730. }(BABYLON.Node));
  101731. BABYLON.PhotoDome = PhotoDome;
  101732. })(BABYLON || (BABYLON = {}));
  101733. //# sourceMappingURL=babylon.photoDome.js.map
  101734. 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;\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\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n#ifdef BILLBOARD \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.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \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 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;\nvec3 worldPos=position+alignedCorner; \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;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin vec2 angle;\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\nvoid main() {\nvUV=uv;\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*size.yz*size.x;\n#ifdef BILLBOARD\n\nvec4 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.z=0.;\nrotatedCorner.w=0.;\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+rotatedCorner);\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nvec3 yaxis=normalize(initialDirection);\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;\n\nvec4 viewPosition=view*vec4(position+alignedCorner,1.0); \ngl_Position=projection*viewPosition;\n#endif\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 float radius;\nuniform float coneAngle;\nuniform float 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\nin vec2 angle;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifdef SIZEGRADIENTS\nout vec3 outInitialSize;\n#endif\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\nout vec2 outAngle;\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\nin vec3 initialSize;\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;\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\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifdef SIZEGRADIENTS\noutInitialSize=outSize;\n#endif \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\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;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (coneAngle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(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(direction,0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutInitialSize=initialSize;\noutSize=initialSize*texture(sizeGradientSampler,vec2(age/life,0)).r;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\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"};
  101735. 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};"};